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

前端 未结 4 823
一生所求
一生所求 2020-12-28 12:44

I create a debounced version of a function with underscore:

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

Once debouncedThing is called...<

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-28 13:01

    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.

提交回复
热议问题