Calling a function every 60 seconds

2018-12-31 17:01发布

问题:

Using setTimeout() it is possible to launch a function at a specified time:

setTimeout(function, 60000);

But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let\'s say).

回答1:

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.



回答2:

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>


回答3:

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


回答4:

In jQuery you can do like this.

function random_no(){
     var ran=Math.random();
     jQuery(\'#random_no_container\').html(ran);
}
           
window.setInterval(function(){
       /// call your function here
      random_no();
}, 6000);  // Change Interval here to test. For eg: 5000 for 5 sec
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>

<div id=\"random_no_container\">
      Hello. Here you can see random numbers after every 6 sec
</div>



回答5:

setInterval(fn,time)

is the method you\'re after.



回答6:

Use window.setInterval(func, time).



回答7:

You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,

function multiStep() {
  // do some work here
  blah_blah_whatever();
  var newtime = 60000;
  if (!requestStop) {
    setTimeout(multiStep, newtime);
  }
}


回答8:

There are 2 ways to call-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

above function will call on every 60 seconds.



回答9:

// 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
  )
}