

Even a high-end macOS system will generate a hole below with the heat produced by running such scripts. When you are using an infinite loop, you literally freeze your browser to death by screwing up the thread that runs your JavaScript code. Unfortunately, both the above methods are pretty messed up. Using an infinite loop that runs till the right time is satisfied.Before ECMA Script 5, we had only two ways of introducing delays in JavaScript.

One such thing is totally covered by SitePoint in their article, Delay, sleep, pause, wait etc in JavaScript. The implementation of such a sleep function, involves "Promisifying" the setTimeout function, and then using the Async/Await syntax to provide a synchronous feel to a rather asynchronous function.There is a huge debate of using delays in JavaScript.

For a quick recap of the syntax involved, see Callback, Promise and Async/Await by Example in JavaScript. We can implement such a sleep function by combining the capabilities of Promises and Async/Await in JavaScript. But this is not to say we can't implement one! Unfortunately, this does not exist natively in JavaScript. console.log("Executing code.") Ī more convenient option would be to have something similar to: console.log("Executing code.") This is due to the fact that setTimeout is an asynchronous function, hence one would have to continue the execution of the code, in the callback passed to it, after the elapsed time. The only problem is, using setTimeout is not as convenient as one would like. JavaScript does not have a similar sleep function, although it has the setTimeout function which can be used to achieve a similar purpose. Not surprising this functionality is often implemented via a function usually named sleep. Most popular mainstream languages have a sleep functionality that allows for the pausing of code execution for a specified amount of time.
