/
functions__throttle.vanilla.js
52 lines (45 loc) · 1.42 KB
/
functions__throttle.vanilla.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
/**
* @module functions__throttle
*/
modules.define('functions__throttle', function(provide) {
var global = this.global;
provide(
/**
* Throttle given function
* @exports
* @param {Function} fn function to throttle
* @param {Number} timeout throttle interval
* @param {Boolean} [invokeAsap=true] invoke before first interval
* @param {Object} [ctx] context of function invocation
* @returns {Function} throttled function
*/
function(fn, timeout, invokeAsap, ctx) {
var typeofInvokeAsap = typeof invokeAsap;
if(typeofInvokeAsap === 'undefined') {
invokeAsap = true;
} else if(arguments.length === 3 && typeofInvokeAsap !== 'boolean') {
ctx = invokeAsap;
invokeAsap = true;
}
var timer, args, needInvoke,
wrapper = function() {
if(needInvoke) {
fn.apply(ctx, args);
needInvoke = false;
timer = global.setTimeout(wrapper, timeout);
} else {
timer = null;
}
};
return function() {
args = arguments;
ctx || (ctx = this);
needInvoke = true;
if(!timer) {
invokeAsap?
wrapper() :
timer = global.setTimeout(wrapper, timeout);
}
};
});
});