用户脚本计时器错误
好的,页面上有一个按钮,我正在尝试更改用 Javascript 完成倒计时的文本。我对这门语言相当陌生(2天),并且不确定我的代码有什么问题。它不会等待整整一秒才再次迭代,而是立即重新迭代。
var c = 15;
function countDown(e){
if (c!=0){
e.value = 'Reply (' + c + ')';
c--;
setTimeout(countdown(e),1000);
}
else{
e.value = 'Reply'}
}
}
但它似乎并没有像我想象的那样花费 15 秒,而是一次性全部触发(通过我在 if 语句中添加 alert('a');
证明,我可以看到按钮文本更改)
我不确定这是 Greasemonkey 的问题还是我的 javascript 的问题。
Okay, so there is a button on a page that I'm trying to change the text of for a count-down done in Javascript. I'm fairly new to the language (2 days), and am not sure as to what is wrong with my code. Instead of waiting the full second before iterating again, it instantly re-iterates.
var c = 15;
function countDown(e){
if (c!=0){
e.value = 'Reply (' + c + ')';
c--;
setTimeout(countdown(e),1000);
}
else{
e.value = 'Reply'}
}
}
but it seems that instead of taking 15 seconds like I assumed, it fires off all at once (proven by me adding in an alert('a');
in the if statement I could see the button text changing)
I'm not sure if it's a problem with Greasemonkey or a problem with my javascript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题在于这一行:
countdown(e)
是对返回 void 的倒计时函数的调用。 setTimeout 函数接受函数引用和超时,因此您需要将其更改为:您当前的代码递归调用 countdown(e) 15 次,然后 setTimeout(void, 1000);
如果您需要 setTimeout 将参数(如
e
)传递给您的函数,您可以在超时后使用可选参数。Your problem is with this line:
countdown(e)
is a call to the countdown function that returns void. The setTimeout function accepts a function reference and a timeout, so you need to change it to:Your current code is calling countdown(e) 15 times recursively and then setTimeout(void, 1000);
If you need setTimeout to pass arguments (like
e
) to your function you can make use of the optional parameters after the timeout.