Skip to main content

Quick tip about setTimeout function

· One min read
Benjamin Auzanneau

In JavaScript, we have the event loop.

So, without Web Workers, JavaScript is single-threaded, non-blocking, asynchronous, concurrent language.

What can I do with the setTimeout function ?

I can launch the execution of a part of your code after a delay.

The delay may be longer than intended.

setTimeout(() => console.log("After the delay"), 5000);

console.log("Before the delay");

// Printed => 'Before the delay'
// After ≈ 5 secondes => 'After the delay'

One more thing

Sometimes you can see this kind of code.

setTimeout(() => {
someHTMLNode.style.color = "yellow";
}, 0);

We are manipulating a property of a node element (it's a DOM element). But the DOM is not ready, someHTMLNode doesn't exist.

ThesetTimeout(fn, 0) is a workaround, we can delay our affection after the DOM rendering !

That's it, make good use of it !


I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover by Icons8 Team on Unsplash