| 1 |
// It's actually "debounce" |
| 2 |
|
| 3 |
"use strict"; |
| 4 |
|
| 5 |
var isValue = require("es5-ext/object/is-value") |
| 6 |
, callable = require("es5-ext/object/valid-callable") |
| 7 |
, nextTick = require("next-tick") |
| 8 |
, validTimeout = require("./valid-timeout"); |
| 9 |
|
| 10 |
var apply = Function.prototype.apply; |
| 11 |
|
| 12 |
module.exports = function (fn/*, timeout*/) { |
| 13 |
var scheduled, run, context, args, delay, timeout = arguments[1], handle; |
| 14 |
callable(fn); |
| 15 |
if (isValue(timeout)) { |
| 16 |
timeout = validTimeout(timeout); |
| 17 |
delay = setTimeout; |
| 18 |
} else { |
| 19 |
delay = nextTick; |
| 20 |
} |
| 21 |
run = function () { |
| 22 |
if (!scheduled) return; // IE8 tends to not clear immediate timeouts properly |
| 23 |
scheduled = false; |
| 24 |
handle = null; |
| 25 |
apply.call(fn, context, args); |
| 26 |
context = null; |
| 27 |
args = null; |
| 28 |
}; |
| 29 |
return function () { |
| 30 |
if (scheduled) { |
| 31 |
if (!isValue(handle)) { |
| 32 |
// 'nextTick' based, no room for debounce |
| 33 |
return; |
| 34 |
} |
| 35 |
clearTimeout(handle); |
| 36 |
} |
| 37 |
scheduled = true; |
| 38 |
context = this; |
| 39 |
args = arguments; |
| 40 |
handle = delay(run, timeout); |
| 41 |
}; |
| 42 |
}; |