因为setTimeInterVal,定时执行,无论是否执行完,在下一个时间点都会继续执行,运行时间长的话会有卡顿等现象。
基于此,改用setTimeOut,setTimeOut只在执行完才执行下一个时间点。在下一个时间点可以清除上个定时器。如此循环不卡顿,亲测可用。
运行了几个小时,一两分钟甚至几秒执行一次,同时执行了几十个这样的写法,完全不消耗资源不卡顿。特此分享。
原生的没试着封装,此基于jq封装的。
$.extend({
myData:[{},{},{}],//数据
seI_autoFn: null,//定时器
autoFnIndex:0,//定时器执行的次数,可判断执行某些东西
autoFn:function (argument) {//如果有需要,加参数
//判断循环次数,如果有需要
// if ($.autoFnIndex < $.myData.length) {
if ($.autoFnIndex < 2) {
//你要执行的方法function()
//或者其他$.autoFn()的方法
//例如定时更新myData的数据
$.autoFnIndex++;
} else {
$.autoFnIndex = 0;
}
//判断循环次数,如果有需要
// if ($.autoFnIndex >= $.myData.length) {
// if ($.autoFnIndex >= 2) {
// $.autoFnIndex = 0;
// }
//每次清空定时器
clearTimeout($.seI_autoFn);
//定时器更新时间
var refushTime = 30*60*1000;
$.seI_autoFn = setTimeout(function() { $.autoFn(argument) }, refushTime);
}
});
别忘了执行定时器
$.autoFn(argument)//可不加参数
还可调用的参数
$.autoFnIndex
$.seI_autoFn
$.myData
requestAnimationFrame,也可试着参考,不过requestAnimationFrame是没有时间设置的,应该每16毫秒刷一次。