简体   繁体   English

Javascript 去抖回调 Function 与动态 Arguments

[英]Javascript Debounce Callback Function with Dynamic Arguments

So for a feature, I have to use the javascript debounce function, which looks like this:所以对于一个功能,我必须使用 javascript debounce function,它看起来像这样:

$.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.我是回调函数的新手,刚刚意识到,这个 function 返回一个我可以调用的 function。 But I can not call it directly.但我不能直接调用它。 However, I want to have dynamic arguments, without creating a new variable function object every time.但是,我想要动态 arguments,而不是每次都创建一个新变量 function object。

So for example I want to call my function所以例如我想打电话给我的 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.但我想让 print_debounce 更有活力。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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