Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the isNumeric module #578

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
implement cancel method to throttle
  • Loading branch information
EvandroLG committed Apr 18, 2021
commit c487b4f6dcbfa35f60c575b5049321bf4be06534
32 changes: 24 additions & 8 deletions packages/function-throttle/index.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,51 @@
module.exports = throttle;

function throttle(fn, interval, options) {
var wait = false;
var timeoutId = null;
var leading = (options && options.leading);
var trailing = (options && options.trailing);

if (leading == null) {
leading = true; // default
}

if (trailing == null) {
trailing = !leading; //default
}

if (leading == true) {
trailing = false; // forced because there should be invocation per call
}

return function() {
var callNow = leading && !wait;
var cancel = function() {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};

var throttleWrapper = function() {
var callNow = leading && !timeoutId;
var context = this;
var args = arguments;
if (!wait) {
wait = true;
setTimeout(function() {
wait = false;

if (!timeoutId) {
timeoutId = setTimeout(function() {
timeoutId = null;

if (trailing) {
return fn.apply(context, args);
}
}, interval);
}

if (callNow) {
callNow = false;
return fn.apply(this, arguments);
return fn.apply(context, args);
}
};

throttleWrapper.cancel = cancel;

return throttleWrapper;
}
15 changes: 15 additions & 0 deletions test/function-throttle/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,18 @@ test('invokes repeatedly when wait is falsey', function(t) {
}, 40);
}, 40);
});

test('cancel delayed function', function(t) {
t.plan(1);

var callCounter = 0;
var fn = throttle(function() {
callCounter++;
}, 200);

fn.cancel();

setTimeout(function() {
t.equal(callCounter, 0);
}, 400);
});