js for loop with settimeout() example
JavaScript[Edit]
+
0
-
0
js for loop with setTimeout() example
1 2 3 4 5 6 7 8// print values from 0 to 9 in the console every second: for (let i = 0; i < 10; i++) { ((index) => setTimeout(() => console.log(index), i * 1000))(i); } // Warning: this solution schedules at once all iterations (it may be not effective for the big amount of the iterations).
[Edit]
+
0
-
0
js for loop with setTimeout() example
1 2 3 4 5 6 7 8 9 10 11 12// print values from 0 to 9 in the console every second: for (var i = 0; i < 10; i++) { (function(index) { setTimeout(function() { console.log(index); }, i * 1000); })(i); } // Warning: this solution schedules at once all iterations (it may be not effective for the big amount of the iterations).
[Edit]
+
0
-
0
js for loop with settimeout() example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22const doLoop = (start, stop, step, delay, callback) => { let i = start; const doIteration = () => { if (i < stop) { callback(i); i += step; setTimeout(doIteration, delay); } }; setTimeout(doIteration, delay); }; // Usage example: doLoop(0, 10, 1, 1000, (index) => console.log(index)); // prints values from 0 to 9 in the console every second // Where: // 0 - iteration start // 10 - iteration stop // 1 - iteration step // 1000 - delay between iterations (1s)