how to delay something in javascript
- Published
- Reading time
- 2 min read
- Length
- 336 words
On this page
How to Delay Something in JavaScript?#
Delaying something in JavaScript can be useful in many scenarios, such as waiting for an animation to finish or delaying an action until a certain condition is met. There are a few ways to delay something in JavaScript:
Using setTimeout()#
The most common way to delay something in JavaScript is by using the setTimeout() method. This method takes two arguments: a function to execute and a time (in milliseconds) to wait before executing that function.
function delayedAction() {
console.log("This action is delayed by 2 seconds.");
}
setTimeout(delayedAction, 2000);In the example above, the delayedAction() function will be executed after a delay of 2 seconds (2000 milliseconds).
Using setInterval()#
The setInterval() method is similar to setTimeout(), but it executes a function repeatedly after a specified time interval.
function repeatedAction() {
console.log("This action is repeated every 2 seconds.");
}
setInterval(repeatedAction, 2000);In the example above, the repeatedAction() function will be executed every 2 seconds (2000 milliseconds).
Using Promises#
Promises are a way to handle asynchronous operations in JavaScript. You can delay an action by wrapping it in a Promise and using the setTimeout() method inside that Promise.
function delayedAction() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("This action is delayed by 2 seconds.");
}, 2000);
});
}
delayedAction().then(function(result) {
console.log(result);
});In the example above, the delayedAction() function returns a Promise that resolves after a delay of 2 seconds. The then() method is used to handle the result of that Promise.
Using async/await#
async/await is a modern way to handle asynchronous operations in JavaScript. You can delay an action by using the await keyword inside an async function with a setTimeout() method.
async function delayedAction() {
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("This action is delayed by 2 seconds.");
}
delayedAction();In the example above, the delayedAction() function is declared as async and uses the await keyword to delay the action for 2 seconds. The code inside the function will be executed after that delay.