Delay execution of code or function in JavaScript
This post will discuss how to delay execution of some code or function in JavaScript. In other words, add a time delay in JavaScript.
There are several ways to add a time delay in JavaScript, depending on how long we want to delay the execution of some code or function. Here are some of the common functions:
1. Using setTimeout() function
One way is to use the setTimeout() function, which is a built-in function that takes two parameters: a callback function and a delay time in milliseconds. The callback function can be either a named function or an anonymous function, and will be executed after the delay time has passed. For example, if we want to log "Hello" message to the console after 2 seconds and "World" message after 3 seconds, we can do this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Define a named function function sayHello() { console.log("Hello"); } // Execute the function after 2 seconds (2000 milliseconds) setTimeout(sayHello, 2000); // Define an anonymous function setTimeout(function() { console.log("World"); // Execute the function after 3 seconds }, 3000); |
2. Using async/await syntax
This syntax allows us to write asynchronous code in a synchronous manner, by using the await keyword to pause the execution of a function until a promise is resolved. A promise is an object that represents the completion or failure of an asynchronous operation. We can create a custom function that returns a promise that resolves after a certain time, and then use the await keyword to pause the execution until the promise is fulfilled. For example, if we want to log a message to the console after 2 seconds, we can do this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Define a custom promise that resolves after a given delay function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Define an async function that uses the delay promise async function sayHelloWorld() { console.log("Hello"); // Pause the function for 2 seconds await delay(2000); console.log("World"); } // Call the async function sayHelloWorld(); |
3. Using Promise
Another way is to use the Promise constructor and the then() function, which are also features of ES6 that allow us to work with asynchronous operations. We can create a new promise that resolves after a certain time, and then use the then() function to execute a callback function when the promise is resolved. For example, if we want to log a message to the console after 2 seconds, we can do this:
|
1 2 3 4 5 |
console.log('Hello'); new Promise(resolve => setTimeout(resolve, 2000)) .then(() => { console.log('World!'); }); |
That’s all about delaying execution of some code or function in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)