| 1 | define(['./now'], function (now) {
|
|---|
| 2 |
|
|---|
| 3 | // Returns a function, that, when invoked, will only be triggered at most once
|
|---|
| 4 | // during a given window of time. Normally, the throttled function will run
|
|---|
| 5 | // as much as it can, without ever going more than once per `wait` duration;
|
|---|
| 6 | // but if you'd like to disable the execution on the leading edge, pass
|
|---|
| 7 | // `{leading: false}`. To disable execution on the trailing edge, ditto.
|
|---|
| 8 | function throttle(func, wait, options) {
|
|---|
| 9 | var timeout, context, args, result;
|
|---|
| 10 | var previous = 0;
|
|---|
| 11 | if (!options) options = {};
|
|---|
| 12 |
|
|---|
| 13 | var later = function() {
|
|---|
| 14 | previous = options.leading === false ? 0 : now();
|
|---|
| 15 | timeout = null;
|
|---|
| 16 | result = func.apply(context, args);
|
|---|
| 17 | if (!timeout) context = args = null;
|
|---|
| 18 | };
|
|---|
| 19 |
|
|---|
| 20 | var throttled = function() {
|
|---|
| 21 | var _now = now();
|
|---|
| 22 | if (!previous && options.leading === false) previous = _now;
|
|---|
| 23 | var remaining = wait - (_now - previous);
|
|---|
| 24 | context = this;
|
|---|
| 25 | args = arguments;
|
|---|
| 26 | if (remaining <= 0 || remaining > wait) {
|
|---|
| 27 | if (timeout) {
|
|---|
| 28 | clearTimeout(timeout);
|
|---|
| 29 | timeout = null;
|
|---|
| 30 | }
|
|---|
| 31 | previous = _now;
|
|---|
| 32 | result = func.apply(context, args);
|
|---|
| 33 | if (!timeout) context = args = null;
|
|---|
| 34 | } else if (!timeout && options.trailing !== false) {
|
|---|
| 35 | timeout = setTimeout(later, remaining);
|
|---|
| 36 | }
|
|---|
| 37 | return result;
|
|---|
| 38 | };
|
|---|
| 39 |
|
|---|
| 40 | throttled.cancel = function() {
|
|---|
| 41 | clearTimeout(timeout);
|
|---|
| 42 | previous = 0;
|
|---|
| 43 | timeout = context = args = null;
|
|---|
| 44 | };
|
|---|
| 45 |
|
|---|
| 46 | return throttled;
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | return throttle;
|
|---|
| 50 |
|
|---|
| 51 | });
|
|---|