Last active
July 13, 2020 04:06
-
-
Save lilywang711/4c3f9c99bbaf2191a8e42e376eb96aff to your computer and use it in GitHub Desktop.
重写 window.setTimeout ,收集所有的 timerId,清除页面上所有定时器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function overrideSetTimeout(fn) { | |
let timerIds = []; | |
function realSetTimeout(callback, delay) { | |
const args = Array.prototype.slice.call(arguments, 2) | |
const timerId = fn(() => { | |
callback.apply(null, args) | |
}, delay) | |
timerIds.push(timerId); | |
return { | |
clear: () => { | |
clearTimeout(timerId); | |
const index = timerIds.findIndex(id => id === timerId); | |
timerIds.splice(index, 1); | |
}, | |
clearAll: clearAll | |
}; | |
} | |
realSetTimeout.clearAll = clearAll; | |
realSetTimeout.getTimerIds = () => { | |
return timerIds; | |
}; | |
return realSetTimeout; | |
function clearAll() { | |
for (const id of timerIds) { | |
clearTimeout(id); | |
} | |
timerIds = []; | |
} | |
} | |
const setTimout = overrideSetTimeout(window.setTimeout); | |
const singleTimeout = setTimout((whom) => { | |
console.log("hello", whom); | |
}, 2000, 'world'); | |
// singleTimeout.clear(); // 清除单个定时器 | |
// setTimout.clearAll(); // 清除所有定时器 | |
setTimout.getTimerIds(); // 获取所有定时器 id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment