2010-06-28 69 views
2

我非常困惑,用setmonout只是无法正常工作,它从来没有调用函数,在网上查找人说greasemonkey不支持setTimeout,有无论如何使我的目标(下)工作?GreaseMonkey倒计时不工作?

function countdown(time, id) { 
    if(document.getElementById(id)) { 
     var name = document.getElementById(id); 
     var hrs = Math.floor(time/3600); 
     var minutes = Math.floor((time - (hrs * 3600))/60); 
     var seconds = Math.floor(time - (hrs * 3600) - minutes * 60); 

     if(hrs>0) { 
      name.innerhtml = hrs + 'h ' + minutes + 'm'; 
     } else if(minutes>0) { 
      name.innerhtml = minutes + 'm ' + seconds + 's'; 
     } else { 
      name.innerhtml = seconds + 's'; 
     } 
    } else { 
     setTimeout('countdown(' + --time + ',' + id + ')', 100); 
    } 

    if(time <= 0) 
     window.location.reload(); 
    else 
     setTimeout('countdown(' + --time + ',' + id + ')', 1000); 
} 

回答

2

问题在于文本参数setTimeout。它可以很好地与greasemonkey配合使用,但如果您使用文本命令而不是回调函数,代码将永远不会执行,因为在启动setTimeout时,greasemonkey沙盒会被清除。它试图运行eval与文本参数wchis轮流尝试调用功能countdown到那时不存在。

目前节目流程如下:

1. function countdown(){} 

2. setTimeout("countdown()", 1000); 

3. clearGreasemonkeySandbox(); 

4. ... wait 1 sec... 

5. eval("countdown()"); // <- countdown doesn't exist anymore 

所以,你应该改用回调,这种方式指向一个功能是用来代替完整的句子。

setTimeout(function(){ 
    countdown(--time, id); 
}, 1000); 
+0

这是基本上是正确的,除非你使用一个字符串,而不是回调的字符串在由到一个函数并在窗口范围内调用,这就是为什么没有找到userscript函数。 userscript的沙箱范围也不会被清除,直到用户离开该页面时(即删除该页面时)。 – erikvold 2010-06-30 05:41:55

1

最后,我结束了使用

window.setTimeout(bla, 1000); 

window.bla = function() { alert("cool"); }

+0

这是因为Amdris说的(我的更正)。 – erikvold 2010-06-30 05:42:57