VisYang's Studio.

setTimeout、setInterval、requestAnimationFrame 三者的区别

2015/11/11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*1. setTimeout*/
//setTimeout-->一次性定时器,想要控制动画则需要递归,每次运行完毕一次定时器后,再次运行
var box1 = document.querySelector('.box1');
var index1 = 0;
var animate = function () {
setTimeout(function () {
index1 ++;
box1.style.left = index1 * 1 + 'px';
animate();
},10);
};
animate();
//clearTimeout(定时器名);//清理定时器
/*2. setInterval*/
//setinterval-->定时器,每次到达指定时间再次执行,不管本次动画是否执行完毕
var box2 = document.querySelector('.box2');
var index2 = 0;
setInterval(function () {
index2 ++;
box2.style.left = index2 * 1 + 'px';
},10);
//clearInterval(定时器名);//清理定时器
/*3. requestAnimationFrame*/
// requestAnimationFrame 根据浏览器每次渲染页面时间自动渲染
var box3 = document.querySelector('.box3');
var index3 = 0;
var action = function () {
index3 ++;
box3.style.left = index3 * 1 + 'px';
/*浏览器有自己的绘制频率 到了渲染时间就通知来执行 action */
requestAnimationFrame(action);
};
action();
//详见下图

prototype1

CATALOG