Home > Net >  Node js returning specific time to setInterval after break
Node js returning specific time to setInterval after break

Time:06-14

I'm studying Nodejs and trying to run this script what loops a function. How to send the time variable to setInterval everytime after the break? In this example The first interval is 15000ms then, when the script continue running, will be changed according whether variable was met. After first and second "ifs", time needs to be 14000ms, then the script will loop again then meet the third and forth "ifs", changing the time to 15000ms again. Not sure if I was clear but here is the code.

let app = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hi');
});
var time = 15000;
function grebData(time)
{

    try{
        if (something1){
            var i=0;
            while(true){
                i  ;
                if(i===1){

                    if (something2){
                        time = 14000;
                    }
                    break;
                }
                       }
                                       
                setTimeout(grebData,time);
            }
        if (something3){
            var i=0;
            while(true){
                i  ;
                if(i===1){
    
                    if (something4){
                        time = 15000;
                        }
                    break;
                }
                           }
                                           
                setTimeout(grebData,time);
            }
        }
    catch (err) {
        console.log(err);
        process.stdin.resume();
    }
};


setTimeout(grebData,time);

app.listen(3001,'0.0.0.0');

CodePudding user response:

You could use setTimeout with the desired time at the end of grebData. You would then also need to replace each existing setInterval with setTimeout.

(setInterval is periodic, setTimeout fires only once.)

I'm not sure about your plans and intentions. But changing the waiting time on the fly would work like this:

var time = 15000;
function grebData(time) {

    try {

        // Your loops, possibly changing the time value

    } catch (err) {
        console.log(err);
        process.stdin.resume();
    }
    setTimeout(grepData,time);
}
setTimeout(grebData,time);

I think you need to realize that when grepData returns, it will not reach the code below it. It's asynchronous.

  • Related