

This time the setTimeout() function will work but not as it is supposed to, as both the console log messages will be displayed at the same time instead of having a delay of 1000 milliseconds between them. log ( "showing after another one second" ), 1000 ) log ( "showing after one second" ), 1000 )

Unlike the sleep() function, if we just put a delay of one second using the setTimeout() method between the lines of JavaScript code, it does not work: In this guide, we will look at several such solutions and explain how we can use the setTimeout() function to pause the execution of JavaScript source code and wait between consecutive lines of code. Unfortunately, the setTimeout() has its own rules and does not work the way the sleep() function does so JavaScript devs have to come up with ingenious solutions to make it work as a sleep() function. This is because they mistake the setTimeout() function to be a version of the sleep() function in JavaScript. It executes the specified piece of code after the timer expires.Ī lot of devs who have worked with the sleep() function find setTimeout() to be confusing. The setTimeout() method is used to set a timer to delay the execution of code. But we can work around this by using the setTimeout() function.

Although it does not work exactly as we expect from the sleep function, we will use it to build our own custom sleep function in javaScript, in this article.įor example, if we need to log three messages to the console with a delay of one second, we can’t do it using the sleep function in JavaScript as it is not available. JavaScript does not have this function, so we use the setTimeout() function to perform the same task. Java has Thread.sleep(2000), Python has time.sleep(2), Go has time.Sleep(2 * time.Second).Sleep is a function that is present in most programming languages and is used to delay the execution of code for a specified time. In a programming language like C or PHP, you’d call sleep(2) to make the program halt for 2 seconds.

Sometimes you want your function to pause execution for a fixed amount of seconds or milliseconds. Learn how to make your function sleep for a certain amount of time in JavaScript
