1. 程式人生 > >移動端事件(五)—— 函式防抖和函式節流的封裝

移動端事件(五)—— 函式防抖和函式節流的封裝

我們瞭解了函式防抖與函式節流的思路後,我們現在來將他們封裝起來,提高程式碼複用性。

今天直接上菜

  cb 要處理防抖的函式
  time 預設的高頻間隔時間
  isStart 是否在頭部執行

函式防抖封裝:呼叫debounce 函式,返回一個處理過防抖的函式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 300px;
            height: 400px;
            background: red;
        }
    </style>
</head>
<body>
<div id="box"></div>    
<script>

function debounce(cb,delay = 200,isStart = false){
    let timer = 0;
    let isFirst = true; //是否是第一次執行
    return function(...arg){
        clearTimeout(timer);
        if(isFirst&&isStart){
            cb.apply(this,arg);
            isFirst = false;
        }
        timer = setTimeout(()=>{
            (!isStart)&&cb.apply(this,arg);
            isFirst = true;
        },delay)
    }
}

box.onmousemove = debounce((e)=>{
    console.log(1);
},200,true);
</script>    
</body>
</html>

 

函式節流封裝:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 300px;
            height: 400px;
            background: red;
        }
    </style>
</head>
<body>
<div id="box"></div>    
<script>
function throttle(cb,interval=200,isStart=false){
    let timer = 0;
    return function(...arg){
        if(timer){
            return ;
        }
        isStart&&cb.apply(this,arg);
        timer = setTimeout(()=>{
            (!isStart)&&cb.apply(this,arg);
            timer = 0;
        },interval)
    }
}
box.onmousemove = throttle(function(e){
    console.log(1,e,this);
},500)   
</script>    
</body>
</html>

以上的封裝都是可以直接使用的,有興趣的看上一篇文章瞭解函式防抖與函式節流的思路會更好。

移動端到此也就告一段落