Rakesh Rakesh - 5 months ago 56
Javascript Question

Execute setTimeout inside for loop after specific time intervals

I want to loop through some numbers i.e. for each iteration loop should execute after specific time period like, 1st iteration should execute on the 1st second, next should execute after 2 seconds and so on...

I am using the flapper plugin to display the numbers. Following is my snippet.



var $lucky = $('.lucky');
$lucky.flapper({
width: 1,
chars_preset: 'alpha',
align: 'right',
timing: 1000,
min_timing: 100,
threshhold: 100,
animation: 'slow',
//transform: true,
});

$(document).ready(function() {
var numbers = ['G', '1', '2', '3', '4', '5', '6'];
var length = numbers.length;
for (var i = 0; i < length; i++) {
console.log(numbers[i]);
var $lucky = $('#lucky' + [i]);
setTimeout(function() {
var $lucky = $('#lucky' + [i]);
var num = numbers[i];
$lucky.val(num).change();
}, 500);
console.log(i);
}
});

.header {
display: inline-block;
}

<div class="container-fluid">
<input class="header light XXL lucky" id="lucky0" />
<input class="header light XXL lucky" id="lucky1" />
<input class="header light XXL lucky" id="lucky2" />
<input class="header light XXL lucky" id="lucky3" />
<input class="header light XXL lucky" id="lucky4" />
<input class="header light XXL lucky" id="lucky5" />
<input class="header light XXL lucky" id="lucky6" />
</div>




Answer

You need to wrap your setTimeout into a IIFE. This is because setTimeout runs asynchronously. The moment it is about to execute after specified time i.e. 500 ms, the loop would be finished by that time.

Here is a modification to your code.

$(document).ready(function() {
    var numbers = ['G', '1', '2', '3', '4', '5', '6'];
    var length = numbers.length;
    for (var i = 0; i < length; i++) {
        (function(i){
            console.log(numbers[i]);
            var $lucky = $('#lucky' + [i]);
            setTimeout(function() {
                var $lucky = $('#lucky' + [i]);
                var num = numbers[i];
                $lucky.val(num).change();
            }, (1000 * i));
        })(i);
    }
});

Wrapping the timeout in that IIFE will capture the value of i in each iteration.

(function(i){
    // loop will execute whatever inside 
    // with a new value of i in each iteration....
})(i);