GreaseMonkey 倒计时不起作用?
我很困惑,greasemonkey setTimeout 不起作用,它从不调用该函数,在网上查看人们说greasemonkey 不支持 setTimeout,有没有办法让我的目标(如下)工作?
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题出在
setTimeout
的文本参数上。它与 Greasemonkey 配合得很好,但如果您使用文本命令而不是回调,则代码永远不会执行,因为在setTimeout
触发时,greasemonkey 沙箱已被清除。它尝试使用文本参数 wchis 运行eval
,然后尝试调用当时已不存在的函数countdown
。目前程序流程如下:
因此您应该使用回调,这样使用指向函数的指针而不是完整的句子。
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 thesetTimeout
fires. It tries to runeval
with the textual parameter wchis in turn tries to call functioncountdown
which doesn't exist by that time anymore.Currently the program flow is as follows:
So you should use callbacks instead, this way a pointer to a function is used instead of the full sentence.
最后我最终使用了
window.bla
= function() {alert("cool"); }
In the end I ended up using
and
window.bla = function() { alert("cool"); }