谁能给我一个简单的解释,关于节流和debounging函数之间的区别,以限制速率的目的。

在我看来,两者的作用是一样的。我查看了这两个博客来找出答案:

http://remysharp.com/2010/07/21/throttling-function-calls

http://benalman.com/projects/jquery-throttle-debounce-plugin/


当前回答

节流阀的简单概念是在表单中频繁点击提交按钮,我们需要使用节流阀。因此提交功能可以防止频繁点击。它将相同的请求保存到函数中。

关于debounce,编写了一个简单的带有输入文本标签的代码,用于从服务器上搜索一些数据。Oninput使用debounce删除之前的请求,并将最后输入的单词传递给服务器

const throttle = (callback, time = 0) => {
    let throttle_req, count = 0;
     return async function () {
         var context = this, args = arguments;  
         if(throttle_req) return;  
         throttle_req = true; 
         if(time > 0)
         {
             callback.apply(context, args); 
             setTimeout(() => {
              throttle_req = false; 
             }, time || 200) 
         }
         else
         {
           let response = await callback.apply(context, args); 
            throttle_req = false; 
           return response;
         } 
     }
  }
const debounce = (callback, time = 0) => {
    let debounce_req;
    return function () {
        var context = this, args = arguments;
        clearTimeout(debounce_req) 
        debounce_req = setTimeout(() => {
             debounce_req = null;
             callback.apply(context, args);
        }, time || 200) 
    }
}

我们如何调用:只是用节流或debounce包装你的函数来检查差异

节流阀:同一按钮点击超过1次

var throttleFunct = throttle(function(num) {
  console.log(num, "hello throttle")
}, 2000);
throttleFunct(300) //it execute. because its the first call
throttleFunct(400) //it won't execute

节流异步没有时间

var getDataAsync =  throttle(function(id, name) {
    return new Promise((resolve) => {  
      setTimeout(() => {
            resolve({name: name, id: id})
      }, 2000)
     }) 
});
async function test() {
let response = await getDataAsync(120, 'Sherley').then(resp => resp)  
console.log(response, "respond") //it execute. because its the first call
response = await getDataAsync(120, 'James').then(resp => resp)  
console.log(response, "respond2")//it executes 2 after first request
response = await getDataAsync(120, 'Jonathan').then(resp => resp)  
console.log(response, "respond3")//it executes 3 after second request
    }
    test()

例如:搜索框自动完成

var debounceFunct = debounce(function(num) {
  console.log(num+1)
}, 2000);
debounceFunct(300) //it won't execute and it cancelled
debounceFunct(400) // it executes and it replaced with the previous call. because this is the latest event fire

其他回答

差异

+--------------+-------------------+-------------------+
|              |  Throttle 1 sec   |  Debounce 1 sec   |
+--------------+-------------------+-------------------+
| Delay        | no delay          | 1 sec delay       |
|              |                   |                   |
| Emits new if | last was emitted  | there is no input |
|              | before 1 sec      |  in last 1 sec    |
+--------------+-------------------+-------------------+

用例解释:

搜索栏-不想搜索每次用户按下键?当用户停止输入1秒时想要搜索。使用debounce 1 SEC按下键。 射击游戏-手枪每次射击之间需要1秒的时间,但用户点击鼠标多次。在鼠标点击时使用油门。

角色互换:

Throttling 1 sec on search bar- If users types abcdefghij with every character in 0.6 sec. Then throttle will trigger at first a press. It will will ignore every press for next 1 sec i.e. bat .6 sec will be ignored. Then c at 1.2 sec will again trigger, which resets the time again. So d will be ignored and e will get triggered. Debouncing pistol for 1 sec- When user sees an enemy, he clicks mouse, but it will not shoot. He will click again several times in that sec but it will not shoot. He will see if it still has bullets, at that time (1 sec after last click) pistol will fire automatically.

进一步解释投入产出与现实生活的比较

酒吧外面有几个警卫。警卫允许说“我去”的人进入酒吧。这是正常的情况。任何说“我去”的人都可以进入酒吧。

现在有一个Throttle Guard(节流5秒)。他喜欢最先回应的人。谁先说“我要去”,他就让那个人去。然后他会在5秒内拒绝每个人。在这之后,无论谁先说,他都会被允许,其他人会被拒绝5秒。

还有另一个弹跳守卫(弹跳5秒)。他喜欢能让他精神休息5秒钟的人。所以如果有人说“我去”,警卫会等5秒钟。如果5秒钟内没有其他人打扰他,他会允许第一个人打扰他。如果有人在这5秒内说“我要去”,他会拒绝第一个。他又开始了等待第二个人的5秒,看第二个人是否能让他得到精神上的休息。

据我所知,简单来说 节流-类似于调用setInterval(回调)的特定次数,即在事件发生的时间内调用同一函数的特定次数 和. . deboundation -类似于调用setTImeout(callbackForApi)或在事件发生后经过一定时间后调用函数。 这个链接很有用 https://css-tricks.com/the-difference-between-throttling-and-debouncing/

油门(1秒):你好,我是机器人。只要你一直打我,我就会继续和你说话,但每次一秒后。如果你在一秒之前ping我的回复,我仍然会在1秒的间隔内回复你。换句话说,我就是喜欢隔一定的时间间隔回复。

弹跳(1秒):嗨,我是那个^^机器人的表弟。只要你一直ping我,我就会保持沉默,因为我喜欢在你最后一次ping我一秒钟后才回复。我不知道,是因为我的态度有问题还是因为我不喜欢打断别人。换句话说,如果您在上次调用后的1秒内一直向我请求回复,您将永远不会得到回复。是的是的…去吧!说我粗鲁就好。


节流阀(10分钟):我是一台伐木机。我将系统日志发送到我们的后端服务器,每隔10分钟。

反弹(10秒):嗨,我不是那台伐木机的表亲。(在这个想象的世界中,并不是每个脱锁器都与节流器有关)。我在附近一家餐馆当服务员。我应该让你知道,只要你一直在你的订单中添加东西,我就不会去厨房执行你的订单。只有在您上次修改订单后10秒后,我才会认为您已经完成了订单。到那时我才会去厨房执行您点的菜。


酷演示:https://css-tricks.com/debouncing-throttling-explained-examples/

服务员类比的功劳:https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

防反跳:

如果函数没有在间隔内被调用,则在间隔后执行函数。

节流:

以固定的时间间隔执行函数n次。

一幅图胜过千言万语

节气门

防反跳

注意Debounce直到事件流停止才会触发。但是,Throttle会在每个间隔时间内触发一个事件。

(感谢css-tricks)