2011-11-27 206 views
3

我需要一个代码,当CheckForZero第一次发生,30秒后再次发生,它每30秒进行一次。延迟功能与greasemonkey

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

回答

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); 
} 
+0

此代码只有一次...我需要它去每30秒 – Riccardo

+0

然后更换的setTimeout()在使用setInterval( )。不过,在初始调用中使用setTimeout(),可以消除cancelInterval()调用。 – sarumont

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