0

I have two js files working together.

  • crawler.js, that contains the code for crawling a website

  • external_functions.js, that contains function to work with in other
    js files

Within the .each() function I would like to have a timeout of 1 second after every loop. The timeout function is defined in the external_functions.js

.each() part of the 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 - the current_time function is obviously irrelevant to this

module.exports = {

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

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

The mentioned solutions do not work because of the each function, so that it`s not a duplicate of another question.

Bindl
  • 81
  • 2
  • 6

1 Answers1

0

two approaches

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

use recursion

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

note that both approaches are not same and intention is to give you a direction

minor PS: after the second argument to setTimeout, following arguments are passed as arguments to callback function 'foo' in our case

ashish singh
  • 6,526
  • 2
  • 15
  • 35