You can set a timeout to execute code at increasing intervals as follows:
var interval = 10 * 1000; // 10 seconds; for (var i = 0; i <=TheUrl.length-1; i++) { setTimeout( function (i) { var url = 'www.myurl.com='+TheUrl[i]; request(url, function(error, resp, body) { if (error) return callback(error); var $ = cheerio.load(body); //Some calculations again... callback(); }); }, interval * i, i); }
So, the first starts immediately (the interval * 0 is 0), the second - after ten seconds, etc.
You need to send i as the final parameter to setTimeout() so that its value is bound to the function argument. Otherwise, an attempt to access the value of the array will be out of bounds, and you will get undefined .
Trott
source share