Skip to content

Instantly share code, notes, and snippets.

@tommmyy
Last active October 19, 2023 15:14
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tommmyy/daf61103d6022cd23d74c71b0e8adc0d to your computer and use it in GitHub Desktop.
Save tommmyy/daf61103d6022cd23d74c71b0e8adc0d to your computer and use it in GitHub Desktop.
Debounce function using Ramda.js
import { curry, apply } from 'ramda';
/**
* Debounce
*
* @param {Boolean} immediate If true run `fn` at the start of the timeout
* @param timeMs {Number} Debounce timeout
* @param fn {Function} Function to debounce
*
* @return {Number} timeout
* @example
*
* const say = (x) => console.log(x)
* const debouncedSay = debounce_(false, 1000, say)();
*
* debouncedSay("1")
* debouncedSay("2")
* debouncedSay("3")
*
*/
const debounce_ = curry((immediate, timeMs, fn) => () => {
let timeout;
return (...args) => {
const later = () => {
timeout = null;
if (!immediate) {
apply(fn, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, timeMs);
if (callNow) {
apply(fn, args);
}
return timeout;
};
});
export const debounceImmediate = debounce_(true);
export const debounce = debounce_(false);
@jackdiff
Copy link

Hi, your solution is very interesting, but at line 26: why don't you use clearTimeout instead of setting timeout= null ?
Looking forward to your response.
Have nice day ! Thanks!

@prdxs
Copy link

prdxs commented Nov 15, 2019

Hi @tommmyy

I would like to know why you chose to return a function that returns a function instead of just returning a function on line 23

  const debounce_ = curry((immediate, timeMs, fn) => () => {
    let timeout;

    return (...args) => { ... };
  });

By the way, thanks for this useful gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment