[Solved] Why is bracket notation not working here? [duplicate]


It’s because variable in for loop is the same in each iteration (same reference) and when setTimeout is running the for loop has ended so the i variable will be last value of the loop, to fix this you can create a closure with i variable:

function play(step){
    var buttons = document.querySelectorAll('.age');
    buttons[0].click();
    for (var i = 1; i < buttons.length; i++){
        (function(i) {
            setTimeout(function(b){
                console.log(i);
                console.log(b);
                b[i].click();
            }, 300 + (step*i), buttons);
        })(i);
    }
}

3

solved Why is bracket notation not working here? [duplicate]