Reputation: 386
My applications need to poll every 2 seconds if there are changes. For now i use setInterval, but sometimes myFunction
takes longer then 2 seconds to execute and records in the mysql database will be inserted twice. I make use of the async lib in myFunction..
So i need this...
When myFunction is finished
method.myFunction() =>
It needs to run again (but only when it is finished). setInterval
with x seconds is not an option. This is because they can run at the same time if the scripts takes longer then x seconds.
How can i run myFunction
again after x seconds, but only when myFunction
is done with processing
So in psuedo code it would be this
if method.myFunction == finished
wait 2 seconds
run method.myFunction again
Upvotes: 1
Views: 3086
Reputation: 386
I used modified your code to this and it works like a charm...
var backup_timeout_seconds = 5000;
var main_rest_seconds = 2000;
function godMethod(timeout){
var backuptimeout = setTimeout(function(){
godMethod(main_rest_seconds);
console.log("Called backup timeout, script is stuck...");
}, backup_timeout_seconds);
Pollforbids.pollForNewBids2(,function (err,res) {
executor(timeout);
clearTimeout(backuptimeout);
});
}
function executor(interval){
setTimeout(function(){
godMethod(interval);
}, interval);
}
godMethod(main_rest_seconds);
Upvotes: -2
Reputation: 356
Use callback or, even better, Promises to let next poll execute only when the previous process is completed.
Upvotes: 1
Reputation: 4736
so with the below code, your method will be called once every seconds when the function execution is over.
function godMethod(){
/* do what ever you want but call executor once you are done with everything */
someCallbackForInsertion(data, function(){
executor()
})
}
function executor(){
setInterval(function(){
godMethod()
}, 2000);
}
executor();
So here you call the executor on start of the server, then after 2 seconds it calls the godMethod then do your insertion/whatever. After successfully inserted call the executor again.
Upvotes: 6