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

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

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

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


当前回答

这篇文章解释得很好,也有图形。

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

从文章中(并进行了一些澄清):

这(节流)和deboundation之间的主要区别在于节流保证了函数的定期执行,至少每X毫秒执行一次。

通常debounce在指定时间结束时调用函数,而throttle在第一次调用节流函数时调用。有时debounce可以采取额外的配置,将此更改为在开始时执行调用。当使用特定的配置调用时,debounce的一些实现实际上可以做油门所做的事情(参见Lodash源代码)。

其他回答

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

关于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

debounging和Throttling是从一系列事件中选择目标以达到减少目标的目的。它们都需要一段时间作为参数,例如:x ms,以及后面/前面的变量来定义如何选择。

消除抖动

当x毫秒后没有其他事件发生时,选择事件

"--->": timeline  "o": event  "|===|": period (x=5)

--oo-o-----ooo-o----o-oo--oo-----o-o-ooo------> events
  |===|    |===|    |===|        |===|
  ||===|   ||===|   | |===|      | |===|   
  |  |===| | |===|  |  |===|     |   |===|
  |      | |   |===||     |===|  |    |===|
  |      | |       ||      |===| |     |===|
---------o---------o-----------o-----------o--> selected events (trailing)
--o--------o--------o------------o------------> selected events (leading)

节流

当有事件发生时,每x毫秒选择一个事件

"--->": timeline  "o": event  "|===|": period (x=5)

--oo-o-----ooo-o----o-oo--oo-----o-o-ooo------> events
  |===|    |===|    |===| |===|  |===||===|
------o--------o--------o-----o------o----o---> selected events (trailing)
--o--------o--------o-----o------o----o-------> selected events (leading)

这篇文章解释得很好,也有图形。

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

从文章中(并进行了一些澄清):

这(节流)和deboundation之间的主要区别在于节流保证了函数的定期执行,至少每X毫秒执行一次。

通常debounce在指定时间结束时调用函数,而throttle在第一次调用节流函数时调用。有时debounce可以采取额外的配置,将此更改为在开始时执行调用。当使用特定的配置调用时,debounce的一些实现实际上可以做油门所做的事情(参见Lodash源代码)。

debound使函数只能在最后一次调用后的一段时间后执行

function debounce(func,wait){
  let timeout
  return(...arg) =>{
    clearTimeout(timeout);
    timeout= setTimeout(()=>func.apply(this,arg),wait)
  }
}


function SayHello(){
  console.log("Jesus is saying hello!!")
}


let x = debounce(SayHello,3000)
x()

节流模式限制了在一段时间内可以调用给定事件处理程序的最大次数。它允许以指定的时间间隔周期性地调用处理程序,忽略该等待期结束之前发生的每个调用。

function throttle(callback, interval) {
  let enableCall = true;

  return (...args)=> {
    if (!enableCall) return;

    enableCall = false;
    callback.apply(this, args);
    setTimeout(() => enableCall = true, interval);
  }
}


function helloFromThrottle(){
  console.log("Jesus is saying hi!!!")
}

const foo = throttle(helloFromThrottle,5000)
foo()

deboning和throttle之间的主要区别在于,debounce在用户未在特定时间内执行事件时调用函数,而throttle在用户执行事件时以指定时间间隔调用函数。