mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-07 18:07:49 +00:00
Fixes #437 -- add an 'immediate' parameter to _.debounce.
This commit is contained in:
@@ -146,6 +146,20 @@ $(document).ready(function() {
|
|||||||
_.delay(function(){ ok(counter == 1, "incr was debounced"); start(); }, 220);
|
_.delay(function(){ ok(counter == 1, "incr was debounced"); start(); }, 220);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
asyncTest("functions: debounce asap", 2, function() {
|
||||||
|
var counter = 0;
|
||||||
|
var incr = function(){ counter++; };
|
||||||
|
var debouncedIncr = _.debounce(incr, 50, true);
|
||||||
|
debouncedIncr(); debouncedIncr(); debouncedIncr();
|
||||||
|
equal(counter, 1, 'incr was called immediately');
|
||||||
|
setTimeout(debouncedIncr, 30);
|
||||||
|
setTimeout(debouncedIncr, 60);
|
||||||
|
setTimeout(debouncedIncr, 90);
|
||||||
|
setTimeout(debouncedIncr, 120);
|
||||||
|
setTimeout(debouncedIncr, 150);
|
||||||
|
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 220);
|
||||||
|
});
|
||||||
|
|
||||||
test("functions: once", function() {
|
test("functions: once", function() {
|
||||||
var num = 0;
|
var num = 0;
|
||||||
var increment = _.once(function(){ num++; });
|
var increment = _.once(function(){ num++; });
|
||||||
|
|||||||
@@ -548,15 +548,17 @@
|
|||||||
|
|
||||||
// Returns a function, that, as long as it continues to be invoked, will not
|
// Returns a function, that, as long as it continues to be invoked, will not
|
||||||
// be triggered. The function will be called after it stops being called for
|
// be triggered. The function will be called after it stops being called for
|
||||||
// N milliseconds.
|
// N milliseconds. If `immediate` is passed, trigger the function on the
|
||||||
_.debounce = function(func, wait) {
|
// leading edge, instead of the trailing.
|
||||||
|
_.debounce = function(func, wait, immediate) {
|
||||||
var timeout;
|
var timeout;
|
||||||
return function() {
|
return function() {
|
||||||
var context = this, args = arguments;
|
var context = this, args = arguments;
|
||||||
var later = function() {
|
var later = function() {
|
||||||
timeout = null;
|
timeout = null;
|
||||||
func.apply(context, args);
|
if (!immediate) func.apply(context, args);
|
||||||
};
|
};
|
||||||
|
if (immediate && !timeout) func.apply(context, args);
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
timeout = setTimeout(later, wait);
|
timeout = setTimeout(later, wait);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user