JavaScript how to pause

Learn how to pause a Javascript program with an example. See how to use the setTimeout() function to put your code on hold.

Pausing JavaScript Execution with setTimeout

JavaScript is an event-driven language, which means that code can be paused and resumed based on user interactions or specific events. The setTimeout() function is a useful tool for pausing JavaScript execution for a set period of time.
setTimeout(function () {
    console.log('Paused for 5 seconds!');
}, 5000);
In the example above, the setTimeout() function takes two arguments. The first argument is a callback function that will be run after the specified delay. The second argument is the delay in milliseconds. So, in this example, the callback function will be executed after 5000 milliseconds (or 5 seconds). It is important to note that setTimeout() does not pause the whole script. It only delays the execution of the callback function. All other code will continue to execute.

For example, if you have a for loop and you call setTimeout() inside the loop, the loop will still run and the callback function will be executed after the specified delay.

for (let i = 0; i < 10; i++) {
    setTimeout(function () {
        console.log('Paused for 5 seconds!');
    }, 5000);
}
In this example, the loop will run 10 times and the callback function will be executed 10 times, with each execution being delayed by 5 seconds.

The setTimeout() function is a powerful tool for delaying the execution of code, and can be used to create interesting effects or to pause code execution until a certain event has occurred.

Answers (0)