13

根据下划线文档

throttle_.throttle(function, wait)
创建并返回传递函数的新的节流版本,当重复调用时,每等待毫秒最多只会实际调用一次原始函数。对于发生得比您跟得上快的限速事件很有用。

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

4

5 回答 5

9

it's not just setTimeout() Try this

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

it will be called once every second and not once every iteration. In native JS it would look like:

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

not exactly the same, but just to illustrate that the function is called once

于 2012-05-01T08:32:40.297 回答
4

扩展达哈泽的回答

更像是,除了 _.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);
    };
}
于 2013-01-14T06:34:51.893 回答
2

我发现这个优秀的 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;
}
于 2014-10-08T23:02:35.023 回答
2

油门和去抖动之间的区别在这里描述: https ://css-tricks.com/the-difference-between-throttling-and-debounce/

/*
"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)
    }
  }
}
于 2017-07-04T20:08:03.013 回答
0

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

于 2017-09-22T08:11:07.977 回答