Search code examples
jquerydelaysetintervalsleep

jQuery setInterval to delay execution in a loop callback


I want to show every hidden row, but sleep 3 seconds between rows.

jQuery.each($('.main-table tbody tr:hidden'),
        function (i, el) {
        setInterval(function(){ 
            $(el).removeClass('hidden');
        }, 3000);
        });

The above sleeps only 3 seconds for the first time. The rest runs right away without pause.


Solution

  • Multiply with the iterator, otherwise they will all execute in 3 seconds as the each loop runs and completes immediately, it doesn't wait for the timeouts to go the next element in the loop.

    jQuery.each($('.main-table tbody tr:hidden'), function (i, el) {
        setTimeout(function(){ 
            $(el).removeClass('hidden');
        }, i * 3000);
    });
    

    note that the first time i will be zero, and 0*3000 == 0, so no timeout.
    If you need a timeout on the first iteration, do (i+1) * 3000