Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
How to cancel a debounced function after it is called and before it executes?

I create a debounced version of a function with underscore:

var debouncedThing = _.debounce(thing, 1000);

Once debouncedThing is called...

debouncedThing();

...is there any way to cancel it, during the wait period before it actually executes?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

If you use the last version of lodash you can simply do:

// create debounce
const debouncedThing = _.debounce(thing, 1000);

// execute debounce, it will wait one second before executing thing
debouncedThing();

// will cancel the execution of thing if executed before 1 second
debouncedThing.cancel()

Another solution is with a flag:

// create the flag
let executeThing = true;

const thing = () => {
   // use flag to allow execution cancelling
   if (!executeThing) return false;
   ...
};

// create debounce
const debouncedThing = _.debounce(thing, 1000);

// execute debounce, it will wait one second before executing thing
debouncedThing();

// it will prevent to execute thing content
executeThing = false;
over 4 years ago · Santiago Trujillo Denunciar

0

Old, but adding a note for anyone else who gets here.

The docs (I'm looking at 1.9.1 right now) say that you should be able to do:

var fn = () => { console.log('run'); };
var db = _.debounce(fn, 1000);
db();
db.cancel();

This would do the thing that the OP wants to do (and what I wanted to do). It would not print the console message.

I have never been able to get this to work. I have looked high and low for a .cancel() as promised in the Underscore doc and I cannot find it.

If you are using Underscore, use the flag option in the accepted answer by Carlos Ruana. My requirements lamentably (in my opinion) do not allow an upgrade (in my opinion) from Underscore to Lodash. Underscore has less functionality but it is more functional than without.

over 4 years ago · Santiago Trujillo Denunciar

0

the Vanilla js variant with cancellable wrap

Note that this solution doesn't require you to modify an external debounce function or to even use an external one. The logic is done in a wrapepr function. Debounce code provided.


The easiest way to allow to cancel an already called function within its debounce period is to call it from a cancelable wrap. Really just add 3 lines of code and an optional condition.

const doTheThingAfterADelayCancellable = debounce((filter, abort) => {
  if (abort) return

  // here goes your code...
  // or call the original function here

}, /*debounce delay*/500)


function onFilterChange(filter) {
  let abort = false

  if (filter.length < 3) { // your abort condition
    abort = true
  }

  // doTheThingAfterADelay(filter) // before
  doTheThingAfterADelayCancellable(filter, abort) // new wrapped debounced call
}

You cancel it by calling it again with abort = true.

The way it works is that it clears the previous timeout fn and sets a new one as it always does, but now with if (true) return path.

You can also do it manually from another code...

doTheThingAfterADelayCancellable(null, true)

...or wrap it and call with cancelBounce()

function cancelBounce() {
  doTheThingAfterADelayCancellable(null, true)
}

For reference, this is your classic debounce function taken from Underscore. It remains intact in my example.

// taken from Underscore.js
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
export function debounce(func, wait, immediate) {
  let timeout
  return function() {
    let context = this, args = arguments
    let later = function() {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    let callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda