起因:
闲来无事和同事交流遇到过那些经典的面试题,同事说有次面试让用用setTimeout实现setInterval并实现clearInterval,话不多说show me code!
function setInv (callback, time) {
const timmer = setTimeout(() => {
setInv(callback, time)
if (!window.isClear) callback()
// 下边这行代码是否有必要呢?
window.clearTimeout(timmer)
}, time)
return timmer
}
function clearInv (timmer) {
window.isClear = true
window.clearTimeout(timmer)
}
const myTask = setInv(() => console.log(Date.now()), 2)
setTimeout(() => {
console.log('清除定时')
clearInv(myTask)
}, 5000)
疑问:
同时也有个问题setTimeout使用过后要不要清楚释放内存,还是说JS底层的垃圾回收会帮我做这件事?跪请大神明示
请戳这里👇在线演示
LiveDemo