Goutham Panneeru
Goutham Panneeru

Reputation: 165

how to use setTimeout more than once simultaneously in nodejs

I have created a http server in node.js and I want a function to run after specific time every time when there is a request. I tried using setTimeout() for this. But the problem is I want multiple timers to be running simultaneously and setTimeout resets each time a new request is made. Can anyone help me on how to do this?

Here is the code which i tried:

http.createServer(getVersion).listen(process.env.PORT, process.env.IP);

function getVersion(req, res) {
    if (url.parse(req.url).pathname === "/") {
    timeout = setTimeout(function() {
        Downloadurls.find({ Downloadurl : randstring }).exec(function (err,result) {
            if (err) { console.log(err) }
            if (!result.length) { 
                Downloadurl_doc = new Downloadurls({
                Downloadurl: randstring
                });
                Downloadurl_doc.save();
            }
        });
    }, timeoutSeconds*1000);
    interval = setInterval(function() {
    console.log('Time left: '+getTimeLeft(timeout)+'s');
    if (getTimeLeft(timeout) === 0)
       { clearInterval(interval);}
    }, 1000);

    function getTimeLeft(randstring1[i]) {
        return Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000);
    }
    }
}

Upvotes: 1

Views: 1635

Answers (1)

balanza
balanza

Reputation: 1079

Maybe this is happening because timeout and interval are declared in the global scope, then they're overridden at each request (they refer to same variable). Instead, try to use var to force those variable to getVersion's function scope:

....
var timeout = setTimeout(function() {
....
var interval = setInterval(function() {
....

I wrote "maybe" because I didn't test it, but makes sense. Anyway, avoid global scope variables if don't needed

Upvotes: 1

Related Questions