just-throttle
Advanced tools
Comparing version 2.1.1 to 2.2.0
@@ -8,4 +8,4 @@ // Definitions by: Dominik Rowicki <https://github.com/papermana> | ||
} | ||
declare function throttle(fn: Function, interval: number, options?: options): Function; | ||
declare function throttle(fn: Function, interval: number, options?: options): Function & {cancel: () => void}; | ||
export = throttle; | ||
export = throttle; |
32
index.js
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) { | ||
@@ -17,10 +20,18 @@ 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) { | ||
@@ -31,7 +42,12 @@ return fn.apply(context, args); | ||
} | ||
if (callNow) { | ||
callNow = false; | ||
return fn.apply(this, arguments); | ||
return fn.apply(context, args); | ||
} | ||
}; | ||
throttleWrapper.cancel = cancel; | ||
return throttleWrapper; | ||
} |
@@ -6,5 +6,5 @@ import throttle = require('./index'); | ||
throttle(() => 'foo', 0); | ||
throttle(() => 'foo', 100); | ||
throttle(() => 'foo', 100); | ||
throttle(() => 'foo', 200, {}); | ||
throttle(() => 'foo', 200, {}); | ||
throttle(() => 'foo', 300, {leading: false, trailing: false}); | ||
@@ -15,2 +15,6 @@ throttle(() => 'foo', 400, {leading: true, trailing: false}); | ||
throttle(() => 'foo', 100).cancel(); | ||
throttle(() => 'foo', 200, {}).cancel(); | ||
throttle(() => 'foo', 400, {leading: true, trailing: false}).cancel(); | ||
// not OK | ||
@@ -17,0 +21,0 @@ |
{ | ||
"name": "just-throttle", | ||
"version": "2.1.1", | ||
"version": "2.2.0", | ||
"description": "return a throttled function", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
## just-throttle | ||
Part of a [library](../../../../) of zero-dependency npm modules that do just do one thing. | ||
Part of a [library](../../../../) of zero-dependency npm modules that do just do one thing. | ||
Guilt-free utilities for every occasion. | ||
@@ -21,2 +21,9 @@ | ||
// forces trailing to false | ||
const fn4 = throttle(() => console.log('hello'), 500, { leading: false }); | ||
fn4(); | ||
fn4(); | ||
fn4(); | ||
fn4.cancel(); | ||
// function cancelled before 'hello' is logged | ||
``` |
4653
75
29