I recently had a need to run a simple for loop in JavaScript, but with a delay (or a pause, or sleep…) of few milliseconds in between iterations. It’s not as simple as I thought, but it can be done, with plane old JavaScript. This is that simple for loop I was talking about:
var words = ['Hello', ', ', 'I ', 'am ', 'in ', 'a ', 'loop', '...'];
for(var i in words)
{
document.getElementById('output').innerHTML += words[i];
sleep(1000);
}
Simple, yes, but it doesn’t work, however you can make something similar to have this functionality, but it won’t be a loop, and it won’t look this simple, but at least it’s possible.
var words = ['Hello', ', ', 'I ', 'am ', 'in ', 'a ', 'loop', '...'];
// (1) define the variable for the array index
var i = 0;
// (2) define the delayed loop function
function delayedLoop()
{
// (3) do action
document.getElementById('output').innerHTML += words[i];
// (4) if the end of the array has been reached, stop
if(++i == words.length)
{
return;
}
// (5) recursively call the delayed loop function with a delay
window.setTimeout(delayedLoop, 1000);
}
delayedLoop(); // (6) start the loop
What is this example doing:
- define the variable for the array index
- define the function which will pose for the loop
- that function does the same action as in the loop in the first example
- make a check if the loop should end
- uses the window.setTimeout(function, delay) to recursively start that function again, but with a 1000 ms delay
- everything above only defined the delayedLoop funcion, so you need to call it to do anything
Working example below:
Output area…