I guess that this could be a duplicate because of the simple nature of the question, but I could not find any answer.
I am setting a Timeout function in a foor loop if a certain condition is true. As I don't want to declare the Timeout within the loop I wrote a setTimeout function to set it outside. I want to use only one timer, which is reset, if it is already running, otherwise the timer should be set the first time. My problem is, that the function sets multiple timers although I am using a clearTimeout().
My code:
var timeout_id;
var things = [true, true, false, true, true];
var setTimer = function(timer_id, duration) {
console.log("timer_id: ", timer_id);
// clear timeout of the given Id
clearTimeout(timer_id);
timer_id = setTimeout(function() {
// reset flag
console.log("Timer timed out");
}, duration);
console.log("timer_id: ", timer_id);
};
for (var i = things.length - 1; i >= 0; i--) {
if (things[i]) {
setTimer(timeout_id, 900);
console.log("Timer set because value of : " + i + " = ", things[i]);
}
}
What I get in the console is:
timer_id: undefined
timer_id: 1
Timer set because value of : 4 = true
timer_id: undefined
timer_id: 2
Timer set because value of : 3 = true
timer_id: undefined
timer_id: 3
Timer set because value of : 1 = true
timer_id: undefined
timer_id: 4
Timer set because value of : 0 = true
timer timed out
timer timed out
timer timed out
timer timed out
I don't understand why my timer_id is increased every time.
I am passing the id and reset the timer of it. After that I am setting a timer on the same Id, ain't I? Is the reference to the var timeout_id not given and changes it from inside the setTimer function?
Thanks for the help.
Change your setTimer function to:
var timer_ids = {};
var setTimer = function(timer_id, duration) {
console.log("timer_id: ", timer_id);
// clear timeout of the given Id
clearTimeout(timer_ids[timer_id]);
timer_ids[timer_id]= setTimeout(function() {
// reset flag
console.log("Timer timed out");
}, duration);
console.log("timer_id: ", timer_id);
};