【问题标题】:Set a timeout within the .each() function [duplicate]在 .each() 函数中设置超时 [重复]
【发布时间】:2018-10-06 07:02:40
【问题描述】:

我有两个 js 文件一起工作。

  • crawler.js,包含用于抓取网站的代码

  • external_functions.js,包含在其他
    中使用的函数 js文件

在 .each() 函数中,我希望在每个循环后有 1 秒的超时。超时函数在 external_functions.js 中定义

.each() 部分爬虫.js

$(".product-tile").each(function(){

    var product = [];

    var product_id = parseInt($(this).attr("data-itemid").replace(/-/g, ""));
    var product_price = $(this).find('div > div.product-information > div.product-price > span.price-sales')
      .text().replace(/(\r\n\t|\n|\r\t)/gm,"");
    var product_brand = $(this).find('div > div.product-information > div.product-name > div.brand')
      .text().replace(/(\r\n\t|\n|\r\t)/gm,"");
    var product_description = $(this).find('div > div.product-information > div.product-name > div.name > a')
      .text().replace(/(\r\n\t|\n|\r\t)/gm,"");
    var product_link = $(this).find('div > div.product-image > a').attr('href');
    var current_time = external_functions.current_time();
    product.push(product_id, product_price, product_brand,product_description, current_time, product_link);
    products.push(product);

    external_functions.timeout_generator();

external_functions.js - current_time 函数显然与此无关

module.exports = {

    current_time: function () {
    return (new Date).toISOString().replace('T', ' ').substr(0, 19);
    },

    timeout_generator: function () {
        setTimeout(function () {
            console.log('Timeout');
        }, 1000);
    },
};

由于每个功能,上述解决方案都不起作用,因此它不是另一个问题的重复。

【问题讨论】:

  • 您的目标是在每次 foreach 迭代之间等待一秒钟吗?
  • @Daryl : 这正是我想要的

标签: javascript node.js settimeout each


【解决方案1】:

两种方法

// setting each execution when intended
counter = 0;
each(function(params) {
    setTimeout( function() { /* do your stuff */} , counter * 1000);
    counter++;
})

使用递归

function foo(params) {
    /* do your stuff */
    setTimeout(foo, 1000, nextParams)
}

请注意,这两种方法并不相同,目的是给你一个方向

小 PS:在 setTimeout 的第二个参数之后,在我们的例子中,以下参数作为参数传递给回调函数 'foo'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多