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

时间:2012-05-01 08:18:14

标签: javascript underscore.js

根据underscore documentation

  

throttle_.throttle(功能,等待)
  创建并返回一个新的,   被调用的传递函数的版本,当被调用时   反复,实际上只会调用一次原始函数   每等待几毫秒。对于速率限制事件很有用   发生得比你能跟上的还要快。

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

5 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:4)

扩展Darhazer's answer

更像是,除了_.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);
    };
}

答案 2 :(得分:1)

我找到了这个帮助我的优秀jsfiddle:

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

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

这样的事情:

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

function getsCalledALot()
{
    a();
}

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

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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