-
Notifications
You must be signed in to change notification settings - Fork 18
/
raf-interval.js
94 lines (84 loc) · 2.49 KB
/
raf-interval.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*!
* raf-interval v0.3.0 By dntzhang
* Github: https://github.com/dntzhang/raf-interval
* MIT Licensed.
*/
;(function() {
if (!Date.now) {
Date.now = function now() {
return new Date().getTime()
}
}
var queue = [],
id = -1,
ticking = false,
tickId = null,
now = Date.now,
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'],
x = 0
for (; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
|| window[vendors[x] + 'CancelRequestAnimationFrame']
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
var currTime = now()
var timeToCall = Math.max(0, 16 - (currTime - lastTime))
var id = window.setTimeout(function () {
callback(currTime + timeToCall)
}, timeToCall)
lastTime = currTime + timeToCall
return id
}
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id)
}
}
window.setRafInterval = function (fn, interval) {
id++
queue.push({id: id, fn: fn, interval: interval, lastTime: now()})
if (!ticking) {
var tick = function () {
tickId = requestAnimationFrame(tick)
each(queue, function (item) {
if (item.interval < 17 || now() - item.lastTime >= item.interval) {
item.fn()
item.lastTime = now()
}
})
}
ticking = true
tick()
}
return id
}
window.clearRafInterval = function (id) {
var i = 0,
len = queue.length
for (; i < len; i++) {
if (id === queue[i].id) {
queue.splice(i, 1)
break
}
}
if (queue.length === 0) {
cancelAnimationFrame(tickId)
ticking = false
}
}
function each(arr, fn){
if(Array.prototype.forEach){
arr.forEach(fn)
}else{
var i= 0,
len=arr.length
for (; i < len; i++) {
fn(arr[i],i)
}
}
}
})();