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

咱們瞭解了函數防抖與函數節流的思路後,咱們如今來將他們封裝起來,提升代碼複用性。html

今天直接上菜app

  cb 要處理防抖的函數
  time 默認的高頻間隔時間
  isStart 是否在頭部執行
函數

函數防抖封裝:調用debounce 函數,返回一個處理過防抖的函數this

<!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>

 

函數節流封裝:spa

<!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>

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

移動端到此也就告一段落了。htm

相關文章
相關標籤/搜索