-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (46 loc) · 1.11 KB
/
index.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
/**
* optimisedEventListener utilising requestAnimationFrame
* Based on MDN's Resize function
* https://developer.mozilla.org/en-US/docs/Web/Events/resize
*/
const optimisedEventlistener = (() => {
const callbacks = []
let running = false
// run the actual callbacks
function runCallbacks() {
callbacks.forEach((callback) => {
callback()
})
running = false
}
// fired on resize event
function eventHandler() {
if (!running) {
running = true
if (window.requestAnimationFrame) {
window.requestAnimationFrame(runCallbacks)
} else {
setTimeout(runCallbacks, 66)
}
}
}
// adds callback to loop
function addCallback(callback) {
if (callback) {
callbacks.push(callback)
}
}
return {
// public method to add additional callback
add: (event, callback) => {
if (!callbacks.length) {
window.addEventListener(event, eventHandler)
}
addCallback(callback)
},
clear: (listener) => {
window.removeEventListener(listener, eventHandler)
}
}
})()
export default optimisedEventlistener