Debounce function implemented with promises

lodash debounce
lodash debounce function promise
jquery debounce
github debounce promise
axios debounce
debounce trailing

I'm trying to implement a debounce function that works with a promise in javascript. That way, each caller can consume the result of the "debounced" function using a Promise. Here is the best I have been able to come up with so far:

function debounce(inner, ms = 0) {
  let timer = null;
  let promise = null;
  const events = new EventEmitter();  // do I really need this?

  return function (...args) {
    if (timer == null) {
      promise = new Promise(resolve => {
        events.once('done', resolve);
    } else {

    timer = setTimeout(() => {
      events.emit('done', inner(...args));
      timer = null;
    }, ms);

    return promise;

Ideally, I would like to implement this utility function without introducing a dependency on EventEmitter (or implementing my own basic version of EventEmitter), but I can't think of a way to do it. Any thoughts?

I found a better way to implement this with promises:

function debounce(inner, ms = 0) {
  let timer = null;
  let resolves = [];

  return function (...args) {    
    // Run the function after a certain amount of time
    timer = setTimeout(() => {
      // Get the result of the inner function, then apply it to the resolve function of
      // each promise that has been created since the last time the inner function was run
      let result = inner(...args);
      resolves.forEach(r => r(result));
      resolves = [];
    }, ms);

    return new Promise(r => resolves.push(r));

I still welcome suggestions, but the new implementation answers my original question about how to implement this function without a dependency on EventEmitter (or something like it).

JavaScript Debounce Function, () { timeout = null; if (! immediate) func. apply(context, args); }; var callNow = immediate && ! timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func. debounce (func, [wait=0], [ {leading: true|false, accumulate: true|false}) Returns a debounced version of func that delays invoking until after wait milliseconds. Set leading: true if you want to call func and return its promise immediately. Set accumulate: true if you want the debounced function to be called with an array of all the arguments received while waiting.

This is my implementation, only last call in interval will be resolved. In Chris's solution all calls will be resolved with delay between them, which is good, but sometimes we need resolve only last call. Correct me, if I'm wrong.

function debounce(f, interval) {
  let timer = null;

  return (...args) => {
    return new Promise((resolve) => {
      timer = setTimeout(
        () => resolve(f(...args)),

Debounce in JavaScript, parameters and the timeout variable on line 9 so that their values are preserved. Debounce with promises. // function debounce ( inner, ms = 0) { let timer = null let resolves = [] return function ( args) {. 2 files.

I landed here because I wanted to get the return value of the promise, but debounce in underscore.js was returning undefined instead. I ended up using lodash version with leading=true. It works for my case because I don't care if the execution is leading or trailing.

_.debounce(somethingThatReturnsAPromise, 300, {
  leading: true,
  trailing: false

Debouncing in JavaScript, not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked. Please explain any assumptions and prerequisites for using the provided debounce function. 2) In the provided example of how to use the debounce function, that function is called with two arguments (a function and a duration). But the debounce function is defined to take three parameters, not two. Please explain why there is a difference in the

No clue what you are trying to accomplish as it vastly depends on what your needs are. Below is something somewhat generic though. Without a solid grasp of what is going on in the code below, you really might not want to use it though.

// Debounce state constructor
function debounce(f) {
  this._f = f;

// Debounce execution function = function() {
  console.log('before check');
  if (this._promise)
    return this._promise;
  console.log('after check');
  return this._promise = this._f(arguments).then(function(r) {
    delete this._promise; // remove deletion to prevent new execution (or remove after timeout?)
    return r;
  }.bind(this)).catch(function(r) {
    console.log('clearing after rejection');
    delete this._promise; // Remove deletion here for as needed as noted above
    return Promise.reject(r); // rethrow rejection

// Some function which returns a promise needing debouncing
function test(str) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      console.log('test' + str);
    }, 1000);

a = new debounce(test); // Create debounced version of function
console.log("p1: ", p1 = a(1));
console.log("p2: ", p2 = a(2));
console.log("p1 = p2", p1 === p2);
setTimeout(function() {
  console.log("p3: ", p3 = a(3));
  console.log("p1 = p3 ", p1 === p3, " - p2 = p3 ", p2 === p3);
}, 2100)

Perform debounce in React.js, (someFunction, 2000), []); const onChange = (event) => { // perform any event related action here handler(); }; a debounce for promises. Contribute to moszeed/es6-promise-debounce development by creating an account on GitHub.

This may not what you want, but can provide you some clue:

 * Call a function asynchronously, as soon as possible. Makes
 * use of HTML Promise to schedule the callback if available,
 * otherwise falling back to `setTimeout` (mainly for IE<11).
 * @type {(callback: function) => void}
export const defer = typeof Promise=='function' ? 
    Promise.resolve().then.bind(Promise.resolve()) : setTimeout;

Debounce with promises · GitHub,​with-promises function debounce (inner, ms = 0) { let timer = null let resolves  The button is attached to an event listener that calls the debounce function. The debounce function is provided 2 parameters – a function and a Number. Declared a variable debounceTimer, which as the name suggests, is used to actually call the function, received as a parameter after an interval of ‘delay’ milliseconds. If the debounce button is clicked only once, the debounce function gets called after the delay.

debouncing-promises.js · GitHub, promise and returns a new function that will execute that method immediately is this behavior which is implemented here, though always-receive-first may. 19 Debounce function implemented with promises Feb 5 '16. 6 Sticky headers in react-virtualized Nov 9 '16. 4 Default back button navigation animation in Android Jun

Introducing the Async Debounce pattern, Promises brought a standard and easy way to handle asynchronous functions. Keep that model in mind and implement each of the hooks then you're As you can see, the debounced function can directly be used to watch  Debounce only works if you wrap your function once, and then call that instance multiple times. (Or maybe there's some IIFE magic happening that makes this work and I just completely missed the point.)

Debounce function implemented with promises, I'm trying to implement a debounce function that works with a promise in javascript. That way, each caller can consume the result of the. The thing I love most about programming is the aha! moment when you start to fully understand a concept. Even though it might take a long time and no small amount of effort to get there, it sure is worth it. I think that the most effective way to assess (and help improve) our degree of comprehension of a given subject is to try and apply the knowledge to the real world. Not only does this let

  • how is debounce function going to be used?
  • @Aprillion It is used as a standard debounce function, like the debounce function provided by lodash, except I want the callers to have access to the return value of the inner function via a promise. Does that answer your question? I can elaborate further if not.
  • This makes sense: the client calling this repeatedly will each time handle the resolved value, and most often you don't want the same value handled multiple times, ... just the last one.
  • This works for me. With the default option ({ leading: false, trailing: true }), the debounced function will return undefined for the first call (and all the following calls unless there is an interval larger than wait).
  • They want a delayed execution.
  • This is not answering the question.