Using setTimeout()
it is possible to launch a function at a specified time:
setTimeout(function, 60000);
But what if I would l
If you don't care if the code within the timer
may take longer than your interval, use setInterval():
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout
along with a self-executing anonymous
function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee
in this example as function reference. It's a better way to give the function a name and call that within setTimeout
because arguments.callee
is deprecated in ecmascript 5.
setInterval(fn,time)
is the method you're after.
A better use of jAndy's answer to implement a polling function that polls every interval
seconds, and ends after timeout
seconds.
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000;
(function p() {
fn();
if (((new Date).getTime() - startTime ) <= timeout) {
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
UPDATE
As per the comment, updating it for the ability of the passed function to stop the polling:
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000,
canPoll = true;
(function p() {
canPoll = ((new Date).getTime() - startTime ) <= timeout;
if (!fn() && canPoll) { // ensures the function exucutes
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
function sendHeartBeat(params) {
...
...
if (receivedData) {
// no need to execute further
return true; // or false, change the IIFE inside condition accordingly.
}
}
Call a Javascript function every 2 second continuously for 10 second.
var intervalPromise; $scope.startTimer = function(fn, delay, timeoutTime) { intervalPromise = $interval(function() { fn(); var currentTime = new Date().getTime() - $scope.startTime; if (currentTime > timeoutTime){ $interval.cancel(intervalPromise); } }, delay); }; $scope.startTimer(hello, 2000, 10000); hello(){ console.log("hello"); }
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
call this line to stop the loop:
clearInterval(timer);
// example:
// checkEach(1000, () => {
// if(!canIDoWorkNow()) {
// return true // try again after 1 second
// }
//
// doWork()
// })
export function checkEach(milliseconds, fn) {
const timer = setInterval(
() => {
try {
const retry = fn()
if (retry !== true) {
clearInterval(timer)
}
} catch (e) {
clearInterval(timer)
throw e
}
},
milliseconds
)
}