今天凌晨写东西的时候遇到的问题, 因为用到setInterval和setTimeout的地方比较多, 懒得改, 便想到了通过重载来实现. 之前只用考虑Safari, 移植到IE之后还有些不一样.
测试了IE8和FF, 都正常. 其他的浏览器应该也没什么问题.
/* 通过重载原有函数实现取消所有Interval和Timeout的功能 请将这段代码放到脚本中靠前的位置, 并确保它在所有setInterval和setTimeout函数被使用之前被解释运行 Vilic Vane (www.vilic.info) ©2010 Groinup */ new function () { //备份原有函数 var _setInterval = window.setInterval; var _setTimeout = window.setTimeout; var _clearInterval = window.clearInterval; var _clearTimeout = window.clearTimeout; //私有计时器列表 var intervalList = []; var timeoutList = []; //重载setInterval window.setInterval = function (code, delay) { var id = _setInterval(code, delay); intervalList.push(id); return id; }; //重载setTimeout window.setTimeout = function (code, delay) { var id = _setTimeout(code, delay); timeoutList.push(id); return id; }; //重载clearInterval window.clearInterval = function (intervalID) { _clearInterval(intervalID); remove(intervalID, intervalList); }; //重载setTimeout window.clearTimeout = function (timeoutID) { _clearTimeout(timeoutID); remove(timeoutID, timeoutList); }; //添加clearAllInterval, 用于取消所有Interval window.clearAllInterval = function () { for (var i = 0; i < intervalList.length; i++) _clearInterval(intervalList[i]); intervalList.length = 0; }; //添加clearAllTimeout, 用于取消所有Timeout window.clearAllTimeout = function () { for (var i = 0; i < timeoutList.length; i++) _clearTimeout(timeoutList[i]); timeoutList.length = 0; }; //私有数组操作函数 function remove(item, from) { for (var i = 0; i < from.length; i++) if (from[i] == item) { from.splice(i, 1); break; } } } ();