I already have tried setInterval(), it seemed perfect but the issue is that it does not initiate the first call immediately and waits for X seconds and then it gives desired value, is there some other way or should I run it an infinite loop and put a sleep like functionality in it?
-
3Does this answer your question? Execute the setInterval function without delay the first timelusc– lusc2021-12-30 07:41:54 +00:00Commented Dec 30, 2021 at 7:41
-
You should try cronjob npmjs.com/package/node-crondivyraj– divyraj2021-12-30 07:47:26 +00:00Commented Dec 30, 2021 at 7:47
Add a comment
|
1 Answer
If your issue is simply it doesn't call for first time then it is OK
function doThis(){
console.log("hello");
}
const time = 1000;
doThis(); // Calls for the first time
setInterval(doThis(),time); // Now it starts the samething.
//There is another option also for same thing:
setInterval(function doThis() {
console.log('hello');
return doThis();
}(), time);
But It is not recommended if function takes longer than delayed time
More on this statement:
https://dev.to/akanksha_9560/why-not-to-use-setinterval--2na9
https://chrisblackwell.me/setinterval-is-bad/
function doThis() {
console.log("hellow");
setTimeout(doThis, 1500);
}
doThis();
The problem that happens with setInterval doesn't happen here, because this only schedules the next iteration, not all future ones.
1 Comment
Miles Prower
If the first line in func() is the settimeout call for the next iteration, won't they be identical or close-to?

