Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

javascript - GreaseMonkey countdown not working?

I'm very confused, with greasemonkey setTimeout just isn't working, it never calls the function, looking online people say greasemonkey doesn't support setTimeout, is there anyway to make my objective (below) work?

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);
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem lies in the textual parameter of setTimeout. It works very well with greasemonkey but if you use textual commands instead of callbacks, the code is never executed since greasemonkey sandbox is cleared by the time the setTimeout fires. It tries to run eval with the textual parameter wchis in turn tries to call function countdown which doesn't exist by that time anymore.

Currently the program flow is as follows:

1. function countdown(){}

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

3. clearGreasemonkeySandbox();

4. ... wait 1 sec...

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

So you should use callbacks instead, this way a pointer to a function is used instead of the full sentence.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...