How can I pause JavaScript code execution for 2 seconds? I want to stop the execution within a loop, like in the following example:
for (var i = 1; i <= 5; i++) {
document.write(i);
sleep(2); // For the first iteration, the loop executes and then pauses for 2 seconds
}
How can I achieve this pause in execution?
In JavaScript, you can’t directly pause execution using something like sleep()
, but you can achieve a pause by using setTimeout()
. Instead of blocking code, JavaScript’s asynchronous nature allows us to set a delay by executing each step of the loop within a callback function. Here’s how you can get that 2-second pause with setTimeout()
:
function pauseLoop(i) {
if (i <= 5) {
document.write(i);
setTimeout(function() {
pauseLoop(i + 1);
}, 2000); // 2000 milliseconds = 2 seconds
}
}
pauseLoop(1);
This recursive approach effectively pauses each iteration by 2 seconds. It’s not truly a “javascript pause,” but it achieves a similar result.
Great solution! Another way to create a javascript pause
is by using async/await
with setTimeout()
. This approach uses Promises, allowing us to make the code look more like a traditional synchronous loop. Here’s how it works:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function loopWithPause() {
for (var i = 1; i <= 5; i++) {
document.write(i);
await delay(2000); // Pause for 2 seconds
}
}
loopWithPause();
By using await
, this code effectively pauses execution within the loop itself, making it look much cleaner. And because await
can only be used in an async
function, we wrap it in loopWithPause()
for that nice 2-second interval.
Great approaches! Yet another way to create a javascript pause
is to use setInterval()
, which repeatedly calls a function at specified intervals. This can be useful here as well to achieve a timed loop:
var i = 1;
var interval = setInterval(function() {
document.write(i);
i++;
if (i > 5) {
clearInterval(interval); // Stop the interval after the loop finishes
}
}, 2000); // Pause for 2 seconds between each iteration
With setInterval()
, you don’t need recursion or async/await; the interval handles the pause between each loop iteration on its own. Just remember to clearInterval()
to avoid an infinite loop after i
reaches 5.