下面是我用clearTimeout实现的一个clearInterval效果,
如何不用clearTimeout()、clearInterval()实现一个自定义的clearInterval()呢?
@小蓝阿姨 @Z_ One Dream
//myclearInterval
function myInterval(func, time) {
let ids = [];
function fn() {
let id = setTimeout(() => {
func();
fn();
}, time)
//console.log(id);
ids.push(id);
}
fn();
return ids;
}
function clearMyInterval(idList) {
idList.forEach((id) => {
clearTimeout(id);
//clearInterval(id)
})
}
function myclearInterval(id) {
setTimeout(() => {
clearMyInterval(id)
}, 0)
}
//-----------------------------------------
var num=0;
let id = myInterval(() => {
//document.write('Hello World');
num++;
if(num===5) myclearInterval(id)
//console.log(num);
// clearMyInterval(id)
console.log(num);
}, 1000)