倒计时的三种写法

你知道定时器有几种吗

小齐:”三种。一者曰setTimeout,再者曰setInterval,三者曰questAnimationFrame”

1. setTimeout
1
2
3
4
5
6
7
8
var a = 10;
var date = new Date();
setTimeout(function () {
console.log(a--);
if (a>=0) {
setTimeout(arguments.callee, 1000);
}
}, 1000);
2. setInterval
1
2
3
4
5
6
7
var a=10;
var t = setInterval(function () {
console.log(a--);
if (a<0) {
clearInterval(t);
}
}, 1000)
3. questAnimationFrame
1
2
3
4
5
6
7
8
9
10
11
12
13
var a=10;
var date = new Date();
requestAnimationFrame(function () {
if(new Date()-date<1000) {
requestAnimationFrame(arguments.callee);
} else {
if (a>=0) {
console.log(a--);
date = new Date();
requestAnimationFrame(arguments.callee);
}
}
})
文章目录
  1. 1. 你知道定时器有几种吗
  2. 2. 1. setTimeout
  3. 3. 2. setInterval
  4. 4. 3. questAnimationFrame