loadash笔记

155 阅读2分钟

官网地址

throttle 节流

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.

If wait is 0 and leading is false, func invocation is deferred until to the next tick, similar to setTimeout with a timeout of 0.

创建一个节流方法,这个方法在每个等待时间内最多只会调用方法一次。这个节流方法带有一个cancel方法来取消引用对象和带有一个flush方法来立即执行它。提供了参数来指示方法会在等待leading时/trailing时执行

简单地说,节流就是指定等待时间内,如果调用了指定方法N次,只会执行第一次。

debounce 防抖

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait timeout.

If wait is 0 and leading is false, func invocation is deferred until to the next tick, similar to setTimeout with a timeout of 0.

防抖是指定时间内调用了指定方法N次,只会执行第一次。

<div id="a1" class="name"> t1 </div>
<div id="a2" class="name"> t1 </div>

<div id="d1" class="name"> d1 </div>
<div id="d2" class="name"> d1 </div>

let tn = _.throttle(function(e,a){console.log('event==',e,a)},1000);
let dn = _.debounce(function(e,a){console.log('event==',e,a)},1000);
document.querySelector('#a1').addEventListener('click', (e)=>tn(e,'a'))
document.querySelector('#a2').addEventListener('click', (e)=>tn(e,'b'))

document.querySelector('#d1').addEventListener('click', (e)=>dn(e,'a'))
document.querySelector('#d2').addEventListener('click', (e)=>dn(e,'b'))