简体   繁体   中英

Javascript Debounce Callback Function with Dynamic Arguments

So for a feature, I have to use the javascript debounce function, which looks like this:

$.debounce = function (func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  };

I am new to callback functions and just realized, that this function returns a function that I can call. But I can not call it directly. However, I want to have dynamic arguments, without creating a new variable function object every time.

So for example I want to call my function

function print_something(){
// prints something
}

I would do it like this:

var print_debounce = $.debounce(print_something, 100);

And then I can use 

print_debounce();

But I want to have the print_debounce more dynamic.

For example (does not work)

var function_debounce = $.debounce(func, wait);

function_debounce(print_something, 100);

Is there any way to do it like this?

Thank you!

I found a way, but it is not very tangible and maybe more complicated than it should.

var debounce_function = function (func, wait, immediate) { return $.debounce(func, wait, immediate); };

debounce_function(print_something, 1000, false).call();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM