In modern web applications, it’s often necessary to wait for a certain amount of time before performing an action. This can be useful for things like creating animations or giving a user a pause before displaying a confirmation message. In this blog post, we’ll discuss how to implement waiting in JavaScript using setTimeout and async/await.
Using setTimeout
setTimeout is a built-in JavaScript function that allows you to execute a function after a specified number of milliseconds. The function takes two arguments: the function to execute and the number of milliseconds to wait before executing it.
Here’s an example of how you can use setTimeout to wait for 3 seconds before executing a function:
[sourcecode]
setTimeout(() => {
console.log('This message will appear after 3 seconds');
}, 3000);
[/sourcecode]
Note that in the example above, we used an arrow function to define the function to be executed after the delay. You can use any kind of function, including a named function or a regular anonymous function.
Using async/await and Promises
If you’re working with modern JavaScript and want a more elegant solution that works well with async functions and promises, you can create a utility function that wraps setTimeout in a promise.
The following function, wait, does just that. It takes one argument – the number of milliseconds to wait – and returns a promise that resolves after the specified amount of time.
[sourcecode]
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
[/sourcecode]
To use the wait function, you can simply call it within an async function and use the await keyword to wait for the promise to resolve. Here’s an example:
[sourcecode]
async function doSomething() {
console.log('Starting…');
await wait(3000);
console.log('This message will appear after 3 seconds');
}
doSomething();
[/sourcecode]
In this example, the doSomething function first logs a message to the console. It then calls the wait function using the await keyword, causing the execution to pause for 3 seconds. After the 3 seconds are up, the promise resolves, and the remaining code in the function will execute.
Conclusion
In this blog post, we’ve explored two techniques for implementing waiting in JavaScript – using setTimeout directly and using a combination of async/await with a custom utility function. By knowing when and how to use these techniques, you can add delays and timing to your JavaScript applications with ease.