JavaScript – Pausing Execution or Sleep Function Equivalent

Javascript Pause/Sleep

JavaScript does not include a sleep function to pause execution – but you can achieve the same effect with this simple code.

Unlike shell scripts and PHP, JavaScript does not include a built-in function to pause execution for a set amount of time.

In other programming languages, this is usually called the sleep function. Unfortunately, JavaScript doesn’t have an equivalent function, but we can build one ourselves!

JavaScript Promises

Modern versions of JavaScript include support for new functionality called promises.

Put simply; a promise is a new kind of object which can be returned by a function when the actual result of the function isn’t ready yet – it’s a promise that the result is on its way. When the result arrives, the promise is resolved, and the value can be used (or any resulting error can be handled).

It means no more waiting for a function to complete before you can do something else – your program moves on, and the promise runs asynchronously until it has been completed.

JavaScript await

The await operator waits for a Promise to resolve before continuing, rather than allowing your program to move on and continue executing while the promise resolves.

JavaScript setTimeout() Function

The setTimeout() function executes a function after a given amount of time defined in milliseconds. The below code prints a message to the console after a 1-second delay:

setTimeout(console.log('hello'), 1000);

Combining await(), Promise and setTimeout() to Pause/Sleep

So, with all of that out of the way, here’s how to pause your JavaScript app from executing:

await new Promise(resolve => setTimeout(resolve, 3000));

await is used to wait for the result of a new Promise, which is set to resolve after a given number of milliseconds (in this case, 3000).

To allow for this to be accomplished in a single line of code rather than over multiple lines, an arrow function expression is used.

And that’s it – if you want to pause or sleep your JavaScript app during execution, place that line where it’s needed and adjust the timing to suit!

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *