Skip to content

Commit

Permalink
Create 最稳定的计时器方式.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rain120 authored Jun 7, 2019
1 parent 18b6e71 commit a4a46a4
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions 最稳定的计时器方式.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// setInterval 虽然时间上设置的是1s,但实际执行,并不是真正意义上的1s,所以长时间或者在其他环境下可能会受到影响
// requestAnimationFrame 则是通过帧数来计算时间, 1000 / 60 = 16.667

// 60s
var last_time = new Date().getTime();
var count = 1;
var countDownId = null;
var countDown = () => {
if (new Date().getTime() - last_time >= 1000) {
count++;
if (count > 60) {
count = 1;
}
console.log(count)
last_time = new Date().getTime();
}
countDownId = window.requestAnimationFrame(countDown);
};
countDownId = window.requestAnimationFrame(countDown);

0 comments on commit a4a46a4

Please sign in to comment.