繁体   English   中英

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

[英]underscore.js: _.throttle(function, wait)

根据下划线文件

throttle_.throttle(功能,等待)
创建并返回传递函数的新的受限制版本,当重复调用时,每次等待毫秒最多只调用一次原始函数。 对于速度限制事件非常有用,这些事件发生得比您能跟上的速度要快。

这意味着Useful for rate-limiting events that occur faster than you can keep up with
这个函数相当于setTimeout,它有一个调用自身的函数?
有人可以在jsfiddle上给我一些例子吗?

它不仅仅是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)
}

不完全相同,只是为了说明函数被调用一次

扩展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);
    };
}

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

jsfiddle.net/max23_/2wn5ybdg/1 (由@ max23_更新)

在我的情况下,我需要节流,因为一个函数(这是一个服务器请求)在1秒内被调用大约500次,并且正在使服务器超载。 所以我改变了它,这样功能只能每3秒调用一次 max。 所以它被调用的次数并不重要,它最多只会每3秒发生一次。

像这样的东西:

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

function getsCalledALot()
{
    a();
}

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

此处描述了油门和去抖动之间的区别: 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)
    }
  }
}

_.throttle用于防止频繁调用特定ms.Refer图像的方法来理解此RestrictfrequentCall.jpg

暂无
暂无

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

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