带润滑脂的延迟功能

时间:2011-11-27 16:46:33

标签: javascript greasemonkey

我需要一个代码,当CheckForZero第一次发生时,30秒后再次发生并且每30秒发生一次。

var waitForZeroInterval = setInterval (CheckForZero, 0);

function CheckForZero ()
{
    if ( (unsafeWindow.seconds == 0)  &&  (unsafeWindow.milisec == 0) )
    {
        clearInterval (waitForZeroInterval);

        var targButton  = document.getElementById ('bottone1799');
        var clickEvent  = document.createEvent ('MouseEvents');

        clickEvent.initEvent ('click', true, true);
        targButton.dispatchEvent (clickEvent);
    }
};

2 个答案:

答案 0 :(得分:5)

您可以简单地跟踪状态:

var hasRun = false;
function CheckForZero () {
    ... snip ...
    if (!hasRun) {
        hasRun = true;
        setInterval(CheckForZero, 30000);
    }
 }

我还建议使用setTimeout()而不是setInterval()/ clearInterval()(因为它不需要经常运行)。

编辑:我编辑了上面的代码以反映OP修改后的要求。我在下面添加了另一个版本来简化。

setTimeout(CheckForZero, 0); // OR just call CheckForZero() if you don't need to defer until processing is complete
function CheckForZero() {
    ... snip ...
    setTimeout(CheckForZero, 30000);
}

答案 1 :(得分:0)

//不需要setInterval,因为它会使事情变得更重

var d = new Date();
var seconds = d.getSeconds()
var milliseconds = d.getMilliseconds()
var msLeft = 60 * 1000 - seconds * 1000 - milliseconds;
unsafeWindow.setTimeout(doSomething,msLeft)

function doSomething(){
   // your work here

   unsafeWindow.setTimeout(doSomething,30000);
}