Skip to content

Instantly share code, notes, and snippets.

@lilywang711
Last active July 13, 2020 04:06
Show Gist options
  • Save lilywang711/4c3f9c99bbaf2191a8e42e376eb96aff to your computer and use it in GitHub Desktop.
Save lilywang711/4c3f9c99bbaf2191a8e42e376eb96aff to your computer and use it in GitHub Desktop.
重写 window.setTimeout ,收集所有的 timerId,清除页面上所有定时器
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