underscore.js: _.throttle(function, wait)

underscore.js: _.throttle(function, wait)

本文关键字:function wait throttle js underscore      更新时间:2023-09-26

根据下划线文档:

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)
}

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

扩展达哈泽的答案

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

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

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

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

就我而言,我需要油门,因为一个函数(这是服务器请求)在 500 秒内被调用了大约 1 次,并且使服务器过载。所以我改变了它,以便该函数每 3 秒只能调用 max 一次。因此,无论调用多少次,它最多每 3 秒只会发生一次。

像这样:

var informationFromServer;
var a = _.throttle(function(){
    informationFromServer = serverCallFunction();
}, 3000);
function getsCalledALot()
{
    a();
}
function serverCallFunction()
{
    var data = $.post....
    return data;
}

_.throttle 用于防止频繁调用特定 ms 的方法。参考图像以了解此限制频率呼叫.jpg