forked from kasparsj/jquery-throttle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.throttle.js
55 lines (46 loc) · 1.4 KB
/
jquery.throttle.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
// requires requestAnimationFrame polyfill
;(function($) {
var callbacks = {};
$.fn.throttle = function(type, callback) {
this.each(function() {
$.throttle(type, callback, this);
});
};
$.fn.removeThrottle = function(type) {
this.each(function() {
$.removeThrottle(type, this);
});
};
$.throttle = function(type, callback, elem) {
var elem = elem || window,
throttleEvent = type+".throttle";
registerCallback(type, callback);
$(elem).off(throttleEvent).on(throttleEvent, function(event) {
throttleFunc(type, event);
});
};
$.removeThrottle = function(type, elem) {
var elem = elem || window;
$(elem).off(type+".throttle");
unregisterCallback(type);
};
function registerCallback(type, callback) {
if (typeof callbacks[type] == "undefined")
callbacks[type] = [];
callbacks[type].push(callback);
}
function unregisterCallback(type) {
delete callbacks[type];
}
var running = false;
function throttleFunc(type, event) {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
for (var i=0; i<callbacks[type].length; i++) {
callbacks[type][i](event);
}
running = false;
});
};
})(jQuery);