DEV Community

Cover image for Quick tip about setTimeout function
Benjamin🦸‍♂️Auzanneau™
Benjamin🦸‍♂️Auzanneau™

Posted on • Updated on

Quick tip about setTimeout function

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'
Enter fullscreen mode Exit fullscreen mode

One more thing

Sometimes you can see this kind of code.

setTimeout(() => {someHTMLNode.style.color = 'yellow'}, 0)
Enter fullscreen mode Exit fullscreen mode

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


Merci d'avoir lu cet article !
Il a été posté initialement sur mon site : https://necraidan.com/blog/back-to-basics-set-timeout

Top comments (0)