Reputation: 11
I have a trouble with setTimeout function in JavaScript, my purpose is to give timeout for each insert statement, after reach given maxrecord, it will pause for 2 hours, then continue the insert statement.
Right now I'm only make a work for first condition which is given delay for each insert. But I don't know how to give 2 hour delay before continue to insert.
my code like this,
var ids = $("#listId").val().split('\n');
var index = 1;
for(var i = 0; i < ids.length; i++) {
(function(i){
setTimeout(function(){
if (index <= interval) {
console.log("INDEX : " + index + " INTERVAL : " + interval);
} else {
console.log("SHOULD BREAK FOR 2 HOURS (NOTHING TODO HERE, JUST DELAY) THEN CONTINUE FROM LAST IDS");
}
index++;
}, 1000 * i);
}(i));
}
as you can see, I need to give 2 hour's delay after index <= interval and then continue again with last i.
Appreciate your help.
Upvotes: 1
Views: 198
Reputation: 324620
You are setting all of your timeouts at once, at the start, with predefined durations.
You cannot (easily) go on to modify how those times are set based on an arbitrary condition (this 2 hour delay you speak of)
Instead, you should do something like:
function nextRow() {
// handle a single row
i++;
if( i < ids.length) setTimeout(nextRow,delay);
// where delay is either 1000 or 7200000 as needed
}
nextRow(); // start the loop
Upvotes: 1