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:

If you have:

console.log(1);setTimeout(() => console.log(2), 0);for(let i = 0; i < 1000; i++) {
console.log(3);
}

Output will be:

1
3
3
...1000 times 3
3
2

As a consequence, code like setTimeout(fn, 0) will execute as soon as the stack is empty, not immediately. If you execute code like setTimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds.

Basic example for using setTimeout():

let fn = setTimeout(() => {
alert('Hello world');
}, 2000);

The browser will wait 2 seconds before displaying that alert.

Passing the third parameter:

function appleCounter(name) {
alert(`${name} has 3 apples`);
}

--

--

Anghel Marius

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