• Stars
    star
    975
  • Rank 45,345 (Top 1.0 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Throttle and debounce functions.

throttle-debounce

Build Status BrowserStack Status Mentioned in Awesome Micro npm Packages

Throttle and debounce functions.

This module is the same as jquery-throttle-debounce (with some differences), but it’s transferred to ES Modules and CommonJS format.

Install

npm install throttle-debounce --save

Usage

throttle

import { throttle } from 'throttle-debounce';

const throttleFunc = throttle(
	1000,
	(num) => {
		console.log('num:', num);
	},
	{ noLeading: false, noTrailing: false }
);

// Can also be used like this, because noLeading and noTrailing are false by default
const throttleFunc = throttle(1000, (num) => {
	console.log('num:', num);
});

throttleFunc(1); // Will execute the callback
throttleFunc(2); // Won’t execute callback
throttleFunc(3); // Won’t execute callback

// Will execute the callback, because noTrailing is false,
// but if we set noTrailing to true, this callback won’t be executed
throttleFunc(4);

setTimeout(() => {
	throttleFunc(10); // Will execute the callback
}, 1200);

// Output
// num: 1
// num: 4
// num: 10

debounce

import { debounce } from 'throttle-debounce';

const debounceFunc = debounce(
	1000,
	(num) => {
		console.log('num:', num);
	},
	{ atBegin: false }
);

// Can also be used like this, because atBegin is false by default
const debounceFunc = debounce(1000, (num) => {
	console.log('num:', num);
});

// Won’t execute the callback, because atBegin is false,
// but if we set atBegin to true, this callback will be executed.
debounceFunc(1);

debounceFunc(2); // Won’t execute callback
debounceFunc(3); // Won’t execute callback

// Will execute the callback,
// but if we set atBegin to true, this callback won’t be executed.
debounceFunc(4);

setTimeout(() => {
	debounceFunc(10); // Will execute the callback
}, 1200);

// Output
// num: 4
// num: 10

Cancelling

Debounce and throttle can both be cancelled by calling the cancel function.

const throttleFunc = throttle(300, () => {
	// Throttled function
});

throttleFunc.cancel();

const debounceFunc = debounce(300, () => {
	// Debounced function
});

debounceFunc.cancel();

The logic that is being throttled or debounced will no longer be called.

To cancel only one upcoming debounced call, you can pass upcomingOnly: true option to cancel function:

const debounceFunc = debounce(300, () => {
	// Debounced function
});

debounceFunc(); // will not be invoked

debounceFunc.cancel({ upcomingOnly: true });

debounceFunc(); // will be invoked

API

throttle(delay, callback, { noLeading, noTrailing, debounceMode })

Returns: Function

Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll.

delay

Type: Number

A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.

callback

Type: Function

A function to be executed after delay milliseconds. The this context and all arguments are passed through, as-is, to callback when the throttled-function is executed.

noTrailing

Type: Boolean

Optional, defaults to false. If noTrailing is true, callback will only execute every delay milliseconds while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed one final time after the last throttled-function call. (After the throttled-function has not been called for delay milliseconds, the internal counter is reset)

noLeading

Type: Boolean

Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that callback will never executed if both noLeading = true and noTrailing = true.

debounceMode

Type: Boolean

If debounceMode is true (at begin), schedule clear to execute after delay ms. If debounceMode is false (at end), schedule callback to execute after delay ms.

debounce(delay, callback, { atBegin })

Returns: Function

Debounce execution of a function. Debouncing, unlike throttling, guarantees that a function is only executed a single time, either at the very beginning of a series of calls, or at the very end.

delay

Type: Number

A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.

callback

Type: Function

A function to be executed after delay milliseconds. The this context and all arguments are passed through, as-is, to callback when the debounced-function is executed.

atBegin

Type: Boolean

Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed delay milliseconds after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call. (After the throttled-function has not been called for delay milliseconds, the internal counter is reset).

Differences with original module

  • Dependancy on jQuery is removed, so if you rely on GUIDs set by jQuery, plan accordingly
  • There is no standalone version available, so don’t rely on $.throttle and $.debounce to be available

Browser support

Tested in Chrome 72, Edge 15, Firefox 65 and should work in all modern browsers (support based on Browserslist configuration).

Test

For automated tests, run npm run test:automated (append :watch for watcher support).

License

Original module license: Copyright (c) 2010 "Cowboy" Ben Alman (Dual licensed under the MIT and GPL licenses. http://benalman.com/about/license/)
This module license: MIT © Ivan Nikolić

More Repositories

1

node-stdlib-browser

Node standard library for browser.
JavaScript
180
star
2

x-autosuggest

Autosuggest results based on input.
JavaScript
66
star
3

postcss-em-media-query

PostCSS plugin for transforming min/max-width/height media queries to ems.
JavaScript
25
star
4

stylelint-no-restricted-syntax

Stylelint rule to disallow specified syntax.
JavaScript
19
star
5

get-sass-vars

Get Sass variables as JSON object.
JavaScript
18
star
6

isomorphic-timers-promises

`timers/promises` for client and server.
JavaScript
18
star
7

modernizr-esm

Modernizr tests as ES Modules.
JavaScript
17
star
8

read-safari-reading-list

Read and parse Safari Reading List.
JavaScript
15
star
9

babel-plugin-native-error-extend

Babel plugin for native `Error` extending.
JavaScript
12
star
10

postcss-query-ast

Query PostCSS AST with CSS selectors.
JavaScript
11
star
11

dotfiles

Home is where the dotfiles are.
Shell
9
star
12

stylelint-no-unresolved-module

Ensures that module (import-like or `url`) can be resolved to a module on the file system.
JavaScript
8
star
13

rationalize.css

Opinionated additions to Normalize.
HTML
8
star
14

sync-safari-reading-list-cli

Sync Safari Reading List to Pinboard bookmarking service.
JavaScript
7
star
15

addic7ed-subtitles-api

API for Addic7ed subtitles.
HTML
6
star
16

babel-plugin-transform-globalthis

Babel plugin for transforming `globalThis`.
JavaScript
5
star
17

browserify-require-async

Browserify transform to handle require.async calls.
JavaScript
5
star
18

sync-safari-reading-list

Sync Safari Reading List to Pinboard bookmarking service.
JavaScript
5
star
19

fetch-google-maps

Load Google Maps API.
JavaScript
4
star
20

string-replace-all-ponyfill

`String.prototype.replaceAll` ponyfill.
JavaScript
3
star
21

array-group-by-ponyfill

`Array.prototype.groupBy` ponyfill.
JavaScript
3
star
22

only-last-promise

Resolve or reject only last Promise.
JavaScript
3
star
23

native-querystring

Node’s querystring module implemented using the built-in URLSeachParams API.
JavaScript
3
star
24

stylelint-number-z-index-constraint

Stylelint rule for setting minimum and maximum constraint value for z-index.
JavaScript
3
star
25

stylelint-sass-render-errors

Display Sass render errors and deprecations as lint errors.
JavaScript
2
star
26

tv-shows-cli

Personal TV shows manager.
JavaScript
2
star
27

sass-scoped-media-query

Scope CSS styles and apply them only inside provided selector and media query pairs.
SCSS
2
star
28

docker-plex-oauth

Docker image for Plex OAuth support.
JavaScript
2
star
29

array-group-by-to-map-ponyfill

`Array.prototype.groupByToMap` ponyfill.
JavaScript
2
star
30

homebrew-pljoska

Personal Homebrew formulae.
Ruby
2
star
31

knowledge

Guides, instructions, tips. Just general development knowledge.
2
star
32

promise-any-ponyfill

`Promise.any` ponyfill.
JavaScript
2
star
33

papir.css

Sensible print stylesheet.
HTML
2
star
34

eslint-config-nitpick

ESLint config for my projects.
JavaScript
2
star
35

statua-dialog

Dialog component.
JavaScript
2
star
36

css-resolution-units

List of CSS resolution units.
2
star
37

regex-oib

Regular expression for OIB.
JavaScript
2
star
38

tint-shade-color

Tint or shade color.
JavaScript
2
star
39

stylelint-config-nitpick

Stylelint config for my projects.
JavaScript
2
star
40

delegate-event-listener

Delegate event listener.
JavaScript
2
star
41

ping-home

Sham-like alternative to Beacon API (http://mdn.io/beacon)
JavaScript
2
star
42

node-sass-global-import-once

Import Sass files once globally.
JavaScript
2
star
43

postcss-media-query-gap

PostCSS plugin for applying gap on max-width/height media queries.
JavaScript
2
star
44

sort-media-queries

Sort media queries.
JavaScript
2
star
45

docker-node-chrome

Docker image with Node and latest Google Chrome.
Shell
2
star
46

bookmarklets

List of bookmarklets I find useful. Also, easy iOS activation of those same bookmarklets.
JavaScript
2
star
47

element-within-viewport

Check if elements are in viewport.
JavaScript
2
star
48

array-string-at

Array/string `.at()` ponyfill.
JavaScript
2
star
49

css-angle-units

List of CSS angle units.
1
star
50

string-match-all

`String.prototype.matchAll` ponyfill.
JavaScript
1
star
51

load-script-p

Load script as promise.
JavaScript
1
star
52

babel-plugin-media-query-gap

Babel plugin for applying gap on max-width/height media queries.
JavaScript
1
star
53

css-time-units

List of CSS time units.
1
star
54

advertol

Advertisement zones manager.
1
star
55

vagrant-selenium

Setup simple Selenium server via Vagrant.
Shell
1
star
56

css-inliner

JavaScript
1
star
57

hascheck

Interface to Hrvatski akademski spelling checker.
JavaScript
1
star
58

delay-image

Delay image load until it’s in viewport.
JavaScript
1
star
59

css-frequency-units

List of CSS frequency units.
1
star
60

css-functions-list

List of standard and browser specific CSS functions.
JavaScript
1
star
61

regex-jmbg

Regular expression for JMBG.
JavaScript
1
star
62

exfetch

Enhanced (un)fetch API which supports abort and progress events.
JavaScript
1
star
63

playground

Testing, testing…
JavaScript
1
star
64

babayaga

Convenient Browserify builds.
JavaScript
1
star
65

st-settings

Sublime Text personal settings.
TypeScript
1
star
66

faux-anchor

Improve anchor and non-anchor elements with primary and secondary actions and callbacks.
JavaScript
1
star
67

node-sass-json-functions

JSON encode and decode functions for node-sass.
JavaScript
1
star
68

parse-human-date-range

Parse human-readable date to range of dates.
JavaScript
1
star
69

postcss-escape-generated-content-string

PostCSS plugin for escaping strings in generated content.
JavaScript
1
star
70

tv-shows

Personal TV shows manager.
JavaScript
1
star
71

babel-plugin-transform-object-hasown

Babel plugin for transforming `Object.hasOwn`.
JavaScript
1
star
72

kist-selectdown

Select with customizable menu.
JavaScript
1
star
73

regex-css-media-query

Regular expression for CSS media query.
JavaScript
1
star
74

kist-tabify

Simple tabs and accordion interface.
JavaScript
1
star
75

parse-safari-reading-list

[UNMAINTAINED] - Parse Safari Reading List and publish it to Pinboard.
JavaScript
1
star
76

webpack-config-niksy

[DEPRECATED] Webpack config for my projects.
JavaScript
1
star
77

generator-paleta

Yeoman generator for my projects.
JavaScript
1
star
78

classlist-multiple-values

Use multiple values for `classList.add` and `classList.remove` methods.
JavaScript
1
star