Reset Timeout of the same timer in a for loop in Javascript
<p>I guess that this could be a duplicate because of the simple nature of the question, but I could not find any answer.</p>

<p>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().</p>

<p>My code:</p>

<pre><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 &gt;= 0; i--) {
        if (things[i]) {
            setTimer(timeout_id, 900);
            console.log("Timer set because value of : " + i + " = ", things[i]);
        }
    }
</code></pre>

<p>What I get in the console is:</p>

<pre><code>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
</code></pre>

<p>I don't understand why my timer_id is increased every time.</p>

<p>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?</p>

<p>Thanks for the help.</p>