Javascript 在.each()函数中设置超时

Javascript 在.each()函数中设置超时,javascript,node.js,settimeout,each,Javascript,Node.js,Settimeout,Each,我有两个js文件一起工作 crawler.js,其中包含用于对网站进行爬网的代码 external_functions.js,其中包含在other中使用的函数 js文件 在.each()函数中,我希望在每次循环后有一个1秒的超时。超时函数在external_functions.js中定义 .crawler.js的每个()部分 $(".product-tile").each(function(){ var product = []; var product_id = par

我有两个js文件一起工作

  • crawler.js,其中包含用于对网站进行爬网的代码

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

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

.crawler.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-当前_时间函数显然与此无关

module.exports = {

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

    timeout_generator: function () {
        setTimeout(function () {
            console.log('Timeout');
        }, 1000);
    },
};
由于每个函数的作用,上述解决方案都不起作用,所以它不是另一个问题的重复。

两种方法

// 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)
}
请注意,这两种方法并不相同,其目的是给您一个方向


次要提示:在setTimeout的第二个参数之后,以下参数作为参数传递给回调函数“foo”(在我们的例子中)

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