DEV Community

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

Posted on • Edited on

2 2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more