Calling a function every 60 seconds

后端 未结 13 2084
情书的邮戳
情书的邮戳 2020-11-22 08:24

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

setTimeout(function, 60000);

But what if I would l

13条回答
  •  抹茶落季
    2020-11-22 09:04

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

提交回复
热议问题