Search code examples
javascriptfunctionfor-loopsettimeout

classList.add() & setTimeout for remove NOT WORKING IN LOOP INSIDE A FUNCTION


setTimeout not working as expected,

classList.add works but when add setTimeout for classList.remove it shows an erron in console as

"VM1578:5 Uncaught TypeError: Cannot read property 'classList' of null"

var clrArr = ["red", "blue", "yellow", "green"];

var randomClr = [];

//Random Color. Gen

function noGen() {
   return Math.floor(Math.random()*4);
}

function randomClrGen() {
    var no = noGen();
    randomClr.push(clrArr[no]);
    console.log(randomClr);    
}

function randomBtnPress() {
    randomClrGen();
    for(var i = 0; i<randomClr.length; i++){
    document.querySelector("."+ randomClr[i]).classList.add("pressed");
    setTimeout(function () {
        document.querySelector("."+ randomClr[i]).classList.remove("pressed");        
    },100);
    };

}

Solution

  • Use let i = 0 instead of var. When using var the context of i is lost by the time setTimeout runs.