

Therefore, setTimeout makes the console.log only fire after 1000 milliseconds (1 second) of the second console.log call. When you run the above code on the browser or with Node.js with node set-timeout.js, it will give the following output: First log message log ( 'Third log message - after 1 second' ) Below is an example of using setTimeout to wait for 1 second in JavaScript: console. The code pushed in the background can later come back with a result. Some code might be pushed in the background and the next line of code is executed. In the most basic terms, it means the code you see may not be executed line by line in sequence.

It is used to execute a function or a piece of code after the timer expires. In JavaScript one of the easiest wait to block the main thread is with setTimeout. In this post, you will learn how to wait for 1 (or x) second in Javascript using setTimeout, promise, and Delay NPM package with a working code example.

It can be done in multiple ways in JavaScript on the browser and Node.js. Call it a wait, sleep, or delay in executing code in JavaScript.
