目的
以下場景往往由于事件頻繁被觸發,因而頻繁執行DOM操作、資源加載等重行為,導致UI停頓甚至瀏覽器崩潰,
window物件的resize、scroll事件- 拖拽時的
mousemove事件 - 射擊游戲中的
mousedown、keydown事件 - 文字輸入、自動完成的
keyup事件
實際上對于window的resize事件,實際需求大多為停止改變大小n毫秒后執行后續處理;而其他事件大多的需求是以一定的頻率執行后續處理,針對這兩種需求就出現了debounce和throttle兩種解決辦法,
throttle(又稱節流)和debounce(又稱去抖)其實都是函式呼叫頻率的控制器,
debounce去抖
當呼叫函式n秒后,才會執行該動作,若在這n秒內又呼叫該函式則將取消前一次并重新計算執行時間,舉個簡單的例子,我們要根據用戶輸入做suggest,每當用戶按下鍵盤的時候都可以取消前一次,并且只關心最后一次輸入的時間就行了,
throttle節流
throttle將一個函式的呼叫頻率限制在一定閾值內,例如1s內一個函式不能被呼叫兩次,
以下為實戰演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">點擊</button>
</body>
<script>
// 防抖
function fangdou(fn,d){
var delay = d || 600
var timer ;
return function(){
var _this =this ;
var arg =arguments;
if(timer){
clearTimeout(timer)
}
timer =setTimeout(function(){
timer =null;
fn.apply(_this,arg)
},delay)
}
}
function jieliu(fn,d){
var delay = d || 600
var timer;
var last;
return function(){
var _this =this ;
var arg =arguments;
var now = +new Date();
if(last && now-last <delay){
clearTimeout(timer);
timer = setTimeout(function() {
last = now;
fn.apply(_this, arg);
}, delay);
}else{
last = now
fn.apply(_this, arg);
}
}
}
// 時間戳
// btn.onclick=function(){
// console.log(111)
// }
// btn.onclick=fangdou(function(){
// console.log(111,this)
// },500)
btn.onclick=jieliu(function(){
console.log(111,this)
},1000)
</script>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/70951.html
標籤:其他
上一篇:小程式中關于紅包雨的實作
