In the example above, we use the
setTimeout() function is a part of the Window interface in the Web APIs, but it's also available in Node.js environments. It accepts two parameters: a callback function and a delay in milliseconds.
callbackFunction: The function to execute after the delay.
delay: The time to wait before executing the function, in milliseconds.
setTimeout() in a Web Page
Here, we've added an event listener to a button. When clicked, it triggers
setTimeout() to display an alert box after a 1-second delay.
As you venture further into web development, you might encounter situations where using
setTimeout() within promises or async functions is beneficial. This allows you to use the modern
async/await syntax for cleaner, more readable code.
waitOneSecond function, we return a promise that resolves after a 1-second delay. Then, in
runWithDelay, we use
await to pause the function execution until the promise is resolved.
setTimeout() is non-blocking, its use within promises and
async/await can help you manage asynchronous code more effectively.
Happy coding, and may your timed executions always be punctual!
Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.