这个 javascript 函数中的 setInterval() 和clearInterval() 有什么问题吗?清除间隔返回未定义
我有以下代码:
var focusIntervalObj = setInterval(function(){
focusDelayCaused++;
console.log(focusDelayCaused);
}, 100);
clearInterval(focusIntervalObj);
我安装了一个萤火虫。
我期望这段代码记录 focusDelayCaused
的值。
但当我执行时,它并没有这样做,而且 clearInterval()
也只是返回未定义。
请指导。
I have the following code:
var focusIntervalObj = setInterval(function(){
focusDelayCaused++;
console.log(focusDelayCaused);
}, 100);
clearInterval(focusIntervalObj);
I am have a firebug installed.
I am expecting this code to log the value of focusDelayCaused
.
But when I execute, it doesn't do so, and also the clearInterval()
simply returns undefined.
Please guide.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在设置间隔并在触发之前清除它。
这可能就是你的想法。这会更简单:
You are setting the interval and clearing it before it fires.
That might be what you are thinking. Which would be simpler as:
继续上面的代码,您将在设置间隔后立即清除它。所以它永远没有机会运行。
在满足某种条件后而不是在设置后立即清除间隔会有所帮助。
Going on the code above, you're immediately clearing an interval just after you've set it. So it never has a chance to run.
Clearing the interval after some sort of condition has been met rather than immediately after setting it would help.
如果您希望某个函数执行一次并且不再执行,请在您的情况下使用 setTimeout:
If you want some function be executed once and never again, use setTimeout, in your case: