每次点击按钮都会重置 setTimeout 吗?
这是我的代码:
var sec = 10;
var timer = setInterval(function() {
$('#timer span').text(sec--);
}, 1000);
它将 setTimeout
设置为 10 秒。我想要一个重置按钮,单击该按钮会延迟 10 秒再次调用 setTimeout
。
Here is my Code:
var sec = 10;
var timer = setInterval(function() {
$('#timer span').text(sec--);
}, 1000);
It sets a setTimeout
for 10 seconds. I want to have a reset button that, clicked, calls setTimeout
again with a 10 seconds delay.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HTML:
JavaScript:
注意:此 JavaScript 代码应放置在 现成的处理程序< /em>。
现场演示: http://jsfiddle.net/QkzNj/
(您可以设置延迟到较小的值,例如
3000
(3 秒) - 这将使测试演示变得更容易。)HTML:
JavaScript:
Note: this JavaScript code should be placed inside a ready handler.
Live demo: http://jsfiddle.net/QkzNj/
(You can set the delay to a smaller value like
3000
(3 seconds) - that will make it easier to test the demo.)您可以通过将
setTimeout()
调用的结果存储到某个变量,然后在单击按钮时将存储的结果传递给clearTimeout()
来实现此目的,在安排新的超时并将其分配回同一变量之前。听起来有点棘手,但实际上非常简单。这是一个示例:
http://jsfiddle.net/kzDdq/
You would do this by storing the result of your
setTimeout()
call to some variable, and then passing the result that you stored toclearTimeout()
when the button is clicked, before scheduling a new timeout and assigning it back to the same variable.Sounds a bit tricky but it's really very simple. Here is an example:
http://jsfiddle.net/kzDdq/