Run function/code after certain time with nodejs

15,883

Solution 1

Actually, setTimeout is asynchronous, so it will not block.

setTimeout(function(){
    // this code will only run when time has ellapsed
}, n * 1000);
// this code will not block, and will only run at the time

Solution 2

Actually setTimeout() does exactly what you are asking for, it does not block and will execute the given function at some time in the future.

However, it can be tricky to understand what's going on in Node.js. I highly recommend making the investment in learning how to use the Promise API. It can be confusing at first, but gives you a very flexible structure for controlling ansynchronous events. Here is an example I wrote as part of learning how to use the Promise API. You will see that it actually uses setTimeout(), but embeds it in a Promise. Hopefully this code is self explanatory and helps you achieve what you need.

/* 
 *  Try out javascript Promise code in Node.js
 *   
 */

"use strict";

function getRandomBoolean() {
    return Math.random() > 0.5;
}

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

for (let i = 0; i < 5; i++) {

    // Create a promise, which will randomly succeed (and call resolve) or
    // fail (and call reject) after a random time interval
    let intervalMS = getRandomInt(5000);
    let promise = new Promise(function (resolve, reject) {
        setTimeout(() => {
            if (getRandomBoolean()) {
                // Success - Call resolver function
                resolve(i+" Hooray!");
            } else {
                // Treat this as an error - Call reject function
                reject(i+" Sorry!");
            }
        }, intervalMS);
    });
    // When the promise is complete, show the results
    promise.then(
            // The first function is the resolve function, to be called 
            // with a result param upon successful completion of async task
            result => console.log("Success: "+result), 
            // Next is reject function, to be called with an error parameter when something failed
            error => console.log("Failure: "+error) 
    );
    // Flow of execution falls through to here without blocking
    console.log ("Created promise "+i+", will complete in "+intervalMS+" ms");
}

If you run the above example in Node.js (or actually it should run in the browser too, I just haven't tested it there) you will see output something like the following:

Created promise 0, will complete in 853 ms
Created promise 1, will complete in 2388 ms
Created promise 2, will complete in 2738 ms
Created promise 3, will complete in 3053 ms
Created promise 4, will complete in 652 ms
Success: 4 Hooray!
Failure: 0 Sorry!
Failure: 1 Sorry!
Success: 2 Hooray!
Success: 3 Hooray!

Note that the "Created promise..." output comes out first, showing you that the execution falls through without blocking.

Share:
15,883
JerryFox
Author by

JerryFox

Software Engineer

Updated on June 04, 2022

Comments

  • JerryFox
    JerryFox almost 2 years

    I am looking for a way to run some code in nodejs after N amount of seconds.

    Tried setTimeout() but it seems to completely block on it until the time is out but this is not what I want since my server is still sending and receiving events.

    Any advice?

    • Ian
      Ian almost 10 years
      setTimeout doesn't block. Provide code and prove it
    • Wio
      Wio almost 10 years
      My only guess would be that the code which you believe to be blocked was put in the callback function, when it should be placed after the setTimeout function call. You will need to post code for us to pinpoint the issue better.
    • JerryFox
      JerryFox almost 10 years
      thank you're right, was using setInterval corrected (N*1000)but passing settimeout a param that was in seconds not ms