为什么clearInterval在函数上不起作用 [英] Why clearInterval doesn't work on a function
本文介绍了为什么clearInterval在函数上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是代码
var t = ()=>{
setInterval(()=>{
console.log('hello')
},1000)
}
t();
clearInterval(t)
为什么clearinterval不会阻止setInterval的执行?
Why the clearinterval does not block execution of the setInterval?
推荐答案
这是因为您需要返回时间间隔的ID并清除该ID.
It's because you need to return the id of the interval and clear that id.
根据文档:
setInterval返回一个间隔ID,该ID唯一地标识 时间间隔,因此您可以稍后通过调用clearInterval()将其删除.
setInterval returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
//function that keeps logging 'hello' on the console
var t = ()=>{
//return the id of the interval
return setInterval(()=>{
console.log('hello')
},1000)
}
//get the id of the interval created by the "t" function
var id = t();
//alerts the id just to see it
alert(id);
//clear it - function will stop executing
clearInterval(id);
参考
https://developer.mozilla.org/en -US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
这篇关于为什么clearInterval在函数上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文