From 6620648bf080f0f8a0579f6318505b9f78273ffb Mon Sep 17 00:00:00 2001 From: trading_peter Date: Fri, 18 Mar 2022 12:54:58 +0100 Subject: [PATCH] Add debounce --- debounce.js | 22 ++++++++++++++++++++++ package.json | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 debounce.js diff --git a/debounce.js b/debounce.js new file mode 100644 index 0000000..1255054 --- /dev/null +++ b/debounce.js @@ -0,0 +1,22 @@ +/** +@license +Copyright (c) 2022 trading_peter +This program is available under Apache License Version 2.0 +*/ + +export const debounce = (cb, delay, immediate) => { + let timeout; + + return (...a) => { + const callNow = immediate && !timeout; + + clearTimeout(timeout); + + timeout = setTimeout(() => { + timeout = null; + if (!immediate) cb.apply(this, a); + }, delay); + + if (callNow) cb.apply(this, a); + }; +}; diff --git a/package.json b/package.json index 289977f..f121e5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tp/helpers", - "version": "1.0.1", + "version": "1.0.2", "description": "", "main": "closest.js", "scripts": {