Function that calls only the last function from the chain of calls with an interval less than the specified time
We support all platforms.
For module bundlers such as Webpack or Browserify.
npm i debounce-wrapper
- Download lib
- Add script to html
<script src="debounce-wrapper.js"></script>
Recommended for learning purposes, you can use the latest version:
<script src="https://cdn.jsdelivr.net/npm/debounce-wrapper/dist/lib/debounce-wrapper.js"></script>
Recommended for production for avoiding unexpected breakage from newer versions:
<script src="https://cdn.jsdelivr.net/npm/debounce-wrapper@0.0.0/dist/lib/debounce-wrapper.js"></script>
debounce-wrapper as an ES6 module.
import debounce from 'debounce-wrapper';
let result = [],
fn = (number) => result.push(number),
callFnWithDebounce = debounce(fn, 500)
callFnWithDebounce(1)
setTimeout(() => callFnWithDebounce(2),300)
setTimeout(() => console.log(result),350)
debounce-wrapper as a Node.js module
const debounce = require('debounce-wrapper');
let result = [],
fn = (number) => result.push(number),
callFnWithDebounce = debounce(fn, 500)
callFnWithDebounce(1)
setTimeout(() => callFnWithDebounce(2),300)
setTimeout(() => console.log(result),350)
Exports a global variable called debounce
. Use it like this
Connect to html file <script src="https://cdn.jsdelivr.net/npm/debounce-wrapper/dist/lib/debounce-wrapper.js" ></script>
<script>
var result = [],
fn = (number) => result.push(number),
callFnWithDebounce = debounce(fn, 500)
callFnWithDebounce(1)
setTimeout(() => callFnWithDebounce(2),300)
setTimeout(() => console.log(result),350)
</script>
debounce-wrapper as an AMD module. Use with Require.js, System.js, and so on.
- Download lib
- Connect to your module loader
requirejs(['debounce-wrapper'], function(debounce) {
var result = [],
fn = (number) => result.push(number),
callFnWithDebounce = debounce(fn, 500)
callFnWithDebounce(1)
setTimeout(() => callFnWithDebounce(2),300)
setTimeout(() => console.log(result),350)
});
Function wrapper, that cancels the previous function call, if time between previous and current call less than ms
fn
- Type:
function
- Description: function that will be called after ms
- Type:
ms
- Type:
number
- Description: time out, after which fn will call
- Type:
NodeJS.Timeout
let result = [],
fn = (number) => result.push(number),
callFnWithDebounce = debounce(fn, 500)
const firstCallTimeoutId = callFnWithDebounce(1)
setTimeout(() => callFnWithDebounce(2),300)
setTimeout(() => {
console.log(firstCallTimeoutId) // => 1, timeout id that you can clear, when you need 'clearTimeout(firstCallTimeoutId)'
}, 400)
setTimeout(() => {
console.log(result) // => [2]
}, 600)
webster6667