setTimeout实现setInterval和clearInterval

function interV (fn, time) {
let res = {
target: '' // 需要注意:利用引用类型保证target一直是最新的
}
function test () {
fn()
res.target = setTimeout(test, time);
}
test()
return res
}

function cv (timer) {
clearTimeout(timer.target)
}

let t = interV(()=> {
console.log(111)
},1000)

setTimeout(() => {
cv(t)
}, 2000);

posted @ 2021-11-11 11:02  乌卡拉卡  阅读(54)  评论(0编辑  收藏  举报