Notes to the future me. I was bitten by this a few times. In case of problems, this is the place where one can find the example and answer.

There is a difference between using var and let inside for loop.

var tasks = [];
var i;
for (var i = 0; i < 3; i++) {
    tasks.push(function() { console.log(i); })
}
tasks.forEach(function(task) { task(); });
// output: 3 3 3
var tasks = [];
for (let i = 0; i < 3; i++) {
    tasks.push(function() { console.log(i); })
}
tasks.forEach(function(task) { task(); });
// output 0 1 2

var behaviour seems always as not intended. Possible workaround for var based approach is to create own clojure.

var tasks = [];
for (var i = 0; i < 3; i++) {
    tasks.push(printFunction(i))
}

function printFunction(input) {
    return function () {
        console.log(input);
    }
}

tasks.forEach(function(task) { task(); });