NodeJS setTimeout() EOL

Cris Ferreira Pires
2 min readMar 31, 2021
Nodejs Env

There are times when we need to delay something in node.

One of the best tools for the job is setTimeout().

setTimeout() and setInterval() are 2 functions implemented by nodejs itself, as they belong to the global object they can be called anywhere in the code, even without the object prefix. On the browser they are available on the window object.

This functions are useful to do repetitive tasks (setInteval()) or to create a delay between tasks (setTimeout()).

Be aware that neither of them block the code execution. So if you have something dependent of work done in the interval/timeout it will break the code.

So what do I mean by EOL, it means end of life and will be the “death timer” of a timeout.

As there is no straight forwards way to get the time left until the exection of the code thats been timed out we need to find a work around.

In NodeJs, we have access to the function uptime() under the process object.

With this we can set a variable with the “time of birth” of our setTimeout(), and calculate its remaining life span.

This will say 14 because setTimeout() is nonblocking and e we are using Math.trunc() meaning it will cut everything beyond the comma, the real value could be something like 14,8099.

So using setInterval() we can get a EOL read every seconds:

The output:

As you can see the interval kept running and went into negative numbers, after all the timeout had already been completed.

To fix that we can call for the interval to stop when the time out executes.

Now upon completion it does in deed exit the program.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet