Calling a function every 60 seconds Calling a function every 60 seconds javascript javascript

Calling a function every 60 seconds


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.


use the

setInterval(function, 60000);

EDIT : (In case if you want to stop the clock after it is started)

Script section

<script>var int=self.setInterval(function, 60000);</script>

and HTML Code

<!-- Stop Button --><a href="#" onclick="window.clearInterval(int);return false;">Stop</a>


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.    }}