Search code examples
node.jswhile-loopwebserverlocalhost

How to call a function each 2 min while webserver is running?


my Problem is to call a function every two minutes WHILE a Webserver is running. So my Server starts like this:

app.listen(1309, function(){
    console.log("server is listening");
    doSomething();
});

And this is my function doSomething()

var doSomething = function(){
    while(true) {
        sleep.sleep(10);
        console.log("hello"); //the original function will be called here as soon as my code works :P
    }
};

So yes the function prints every 10 seconds (10 sec 'cause testcase, don't want to wait 2 min atm) after starting my webserver but then it can't receive any get requests. (tested this with console.log)

I tried it without the function and it receives them. So I guess the while loop blocks the rest of the sever. How can I call this function every 2 minutes (or 10 sec) while the server is running and without missen any requests to it ?


Solution

  • You need to use setInteval function:

    const 2mins = 2 * 60 * 1000;
    var doSomething = function() {
       setInterval(function() {
         console.log("hello");
       }, 2mins);
    }