码迷,mamicode.com
首页 > Web开发 > 详细

js定时器优化

时间:2019-01-05 18:18:45      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:间隔   fse   date()   pre   ons   结果   amp   span   code   

先看以下两看计时器

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定时器优化

标签:间隔   fse   date()   pre   ons   结果   amp   span   code   

原文地址:https://www.cnblogs.com/7qin/p/10225220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!