0

I am trying to update CSS for all divs (one by one) with a certain class using plain Javascript loop. Here it is:

    var timerCoinRow = 0;
    var rows = document.querySelectorAll('.coin-row');
    for (var i=0; i<rows.length; i++) 
    {
        timerCoinRow += 500;
        obj = rows[i];  

        setTimeout(function () 
        {

            obj.style.opacity = 1;

        }, timerCoinRow);

    }

for some reason it does not work. here is JQuery version that works fine but I need it in plain "vanilla" Javascript:

var timerCoinRow = 0;
    $('.coin-row').each(function () 
    {
        timerCoinRow += 500);
        var obj =$(this);
        setTimeout(function () 
        {

            obj.css('opacity', '1');

        },timerCoinRow,obj);

    });

When I place obj.style.opacity = 1; outside the timeout - all divs are updated but simultaneously while I need them to appear one after another with a pause of 500ms. Please help - it's somewhere near but ....

Rossitten
  • 1,140
  • 1
  • 16
  • 34
  • 1
    `obj` is updated to the last `
    ` after the `for` loop finishes, so all `setTimeout` calls are going to only affect the last one. Use `let`, or the third `setTimeout` parameter, or a closure.
    – Sebastian Simon Nov 20 '17 at 05:25
  • @Xurfox - thanks a bunch, man! "LET" has solved the problem. But, in case this question will be seen by others - what did you mean by "third setTimeout" and "or a closure" ? Thanks once again! – Rossitten Nov 20 '17 at 05:31
  • 1
    Closures are explained in the link, the third parameter (or any optional paramater after the second one) is explained in the docs for [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). – Sebastian Simon Nov 20 '17 at 05:34

0 Answers0