underscore.js:_.throttle(函数,等待)(underscore.js: _.t

2019-07-29 05:32发布

根据下划线文件 :

throttle_.throttle(函数,等待)
创建并返回一个新的,节流的传递函数的版本,即,反复调用时,只能实际调用原函数每每等待的毫秒最多一次。 有用的发生的速度比你能跟上限速事件。

这是什么意思Useful for rate-limiting events that occur faster than you can keep up with
此功能相当于的setTimeout与调用自身的函数?
有人可以提供我上的jsfiddle一些例子吗?

Answer 1:

它不只是的setTimeout()试试这个

var a = _.throttle(function(){console.log('called')}, 1000);
while(true) {
  a();
}

它会被称为每秒一次,每一次迭代不是一次。 在纯JS它会是什么样子:

var i = null;
function throttle(func, delay){
  if (i) {
      window.clearTimeout(i);
  }
  i = window.setTimeout(func, delay)
}

不完全一样,但只是为了说明该函数被调用一次



Answer 2:

为了延长Darhazer的答案

它更像是,除了_.throttle之后迫切呼吁,然后再次delay毫秒

function throttle(func, delay) {
    var timer = 0;

    return function() {
        var context = this,
            args = [].slice.call(arguments);

        clearTimeout(timer);
        timer = setTimeout(function() {
            func.apply(context, args);
        }, delay);
    };
}


Answer 3:

我发现这个优秀的jsfiddle,帮助我:

http://jsfiddle.net/amyseqmedia/dD99u/37/

在我的情况下,我需要节流,因为一个函数(这是一个服务器请求)中的溶液被称为在1秒内500次左右,并被服务器过载。 所以我改变了它,这样的功能只能一次元3秒调用一次最多。 所以不要紧它调用多少次,它只会出现一次,每次最长3秒。

事情是这样的:

var informationFromServer;
var a = _.throttle(function(){
    informationFromServer = serverCallFunction();
}, 3000);

function getsCalledALot()
{
    a();
}

function serverCallFunction()
{
    var data = $.post....
    return data;
}


Answer 4:

油门和去抖之间的差异描述如下: https://css-tricks.com/the-difference-between-throttling-and-debouncing/

/*
"Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
"Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer."
*/
_.debounce = (fn, delay) => {
  let timer
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(null, args)
    }, delay)
  }
}
/*
"Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
 */
_.throttle = (fn, delay) => {
  let canCall = true
  return (...args) => {
    if (canCall) {
      fn.apply(null, args)
      canCall = false
      setTimeout(() => {
        canCall = true
      }, delay)
    }
  }
}


Answer 5:

_.throttle是用来防止在方法调用频繁特定ms.Refer图像理解这RestrictfrequentCall.jpg



文章来源: underscore.js: _.throttle(function, wait)