-
Notifications
You must be signed in to change notification settings - Fork 0
/
raf-debouncer.js
110 lines (86 loc) · 2.21 KB
/
raf-debouncer.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var rafDebounce = (function( window ){
"use strict";
var raf = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var lastScrollY = 0,
lastWidth = window.innerWidth,
lastHeight = window.innerHeight;
var state = {};
for ( var i = 0, e = ["scroll","resize"]; i < e.length; i++ ) {
state[ e[i] ] = {
listening: false,
ticking: false,
queue: {}
};
}
state.scroll.handler = function( evt ) {
lastScrollY = window.scrollY;
if ( ! state.scroll.ticking ) {
processQueue("scroll", [ lastScrollY ] );
}
};
state.resize.handler = function( evt ) {
lastWidth = window.innerWidth;
lastHeight = window.innerHeight;
if ( ! state.resize.ticking ) {
processQueue("resize", [ lastWidth, lastHeight ] );
}
};
function processQueue( type, args ) {
var s = state[ type ],
q = s.queue;
if ( !s.ticking ) {
raf( function(){
var queue;
s.ticking = false;
for ( var i in q ) {
queue = q[i];
for ( var f = 0, len = queue.length; f < len; f++ ) {
queue[ f ].apply( window, args );
}
}
});
}
s.ticking = true;
}
return {
on: function( type, key, callback ) {
if ( typeof key === "function" ) {
callback = key;
key = "anon";
}
var s = state[ type ],
q = s.queue;
if ( ! q[ key ] ) {
q[ key ] = [];
}
q[ key ].push( callback );
if ( ! s.listening ) {
window.addEventListener( type, s.handler, false );
}
},
off: function( type, key ) {
if ( typeof key !== "string" ) {
key = "anon";
}
var s = state[ type ],
q = state.queue,
keys = false;
delete q[ key ];
for ( var i in q ){
keys = true;
break;
}
if ( keys ) {
window.removeEventListener( type, s.handler, false );
s.listnening = false;
}
}
};
})( this );