js定时器优化
Posted 笠航
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js定时器优化相关的知识,希望对你有一定的参考价值。
先看以下两看计时器
setInterval
function sleep(time) { let startTime = window.performance.now(); while (window.performance.now() - startTime < time) {} } function test(){ count++; console.log(`第${count}次开始 ${getTime.now() - startTime}`); // 显示开始时间 //sleep(100); // 程序滞留500ms console.log(`第${count}次结束 ${getTime.now() - startTime}`); // 显示结束时间 count>1000 && clearInterval(t); } let count = 0; let getTime = window.performance; let startTime = getTime.now(); var t = setInterval(test , 500); // 300ms间隔
最后结果:
再来看下setTimeout
function sleep(time) { let startTime = window.performance.now(); while (window.performance.now() - startTime < time) {} } function test(){ console.log(`第${count}次开始 ${getTime.now() - startTime}`); // 显示开始时间 //sleep(500); // 程序滞留500ms console.log(`第${count}次结束 ${getTime.now() - startTime}`); // 显示结束时间 count += 1; if(count<1000){setTimeout(test,500);} } var startTime0 = new Date().getTime(); let count = 0; let getTime = window.performance; let startTime = getTime.now(); var t; //setTimeout(test,500); // 300ms间隔 setTimeout(function () { console.log(`第${count}次开始 ${getTime.now() - startTime}`); // 显示开始时间 //sleep(500); // 程序滞留500ms console.log(`第${count}次结束 ${getTime.now() - startTime}`); // 显示结束时间 count += 1; var offset = new Date().getTime() - (startTime0 + count * 500); var nextTime = 500 - offset; //console.log(nextTime); if (nextTime < 0) nextTime = 0; if(count<200){setTimeout(arguments.callee, nextTime);} }, 500)
以上是关于js定时器优化的主要内容,如果未能解决你的问题,请参考以下文章
优化 C# 代码片段、ObservableCollection 和 AddRange