All You Need to Know About setTimeout in Javascript

setTimeout() in a nutshell in Javascript.

Anghel Marius
2 min readFeb 19, 2022
Screenshot by Author

Firstly, let’s start with the beginning.

What is setTimeout()?

setTimeout() executes the call once after a specified period of time. It takes the following parameters.

  • a callback function to run after the specified period of time
  • a number that represents period of time in milliseconds, 1000 milliseconds = 1 second, you can pass 0 as a milliseconds, but the callback will be executed as soon as possible.

Note: If you pass 0 as the milliseconds parameter of the setTimeout(), the code will be executed as soon as possible. It will be executed when the stack will be empty, not immediately. If you have this block of code

console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);

The output will be:

1
3
2

Why?

As I said below, the stack need to be empty, and the callback from setTimeout() will run as soon as possible. In our case, it will run after the last console.log

Another example:

--

--

Anghel Marius
Anghel Marius

Written by Anghel Marius

Web developer who is enthusiast about new technologies and self-improvement. | https://linktr.ee/anghelm

Responses (1)