js

防抖节流

2020-05-19  本文已影响0人  马甲要掉了

防抖

<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
    <title>debounce</title>
    <style>
        
        #box{
            width: 200px;
            height: 200px;
            background-color: aquamarine;
        }
    </style>
</head>

<body>
   
    <div id="box"></div>
    <script src="debounce.js"></script>
</body>

</html>
function debounce(fn,time){
    let timeout;
    return function(){
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this,arguments);  //将 this 指向正确的对象(否则指向window),此处正确的对象为box
        }, time);
    }
}
function sayhi(){
    console.log("hello lin");
}

let box = document.getElementById('box');
box.addEventListener('click',debounce(sayhi,2000));

节流

function throttle(fn,time){
    let flag = true;
    return function(){
        if(!flag) return;
        flag = false;
        setTimeout(() => {
            fn.apply(this,arguments);
            flag = true;
        }, time);
    }
}
function sayhi(){
    console.log("hello li");
}

let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));

注意

JavaScript 在事件处理函数中会提供事件对象 event,如果不加arguments

function throttle(fn,time){
    let flag = true;
    return function(){
        if(!flag) return;
        flag = false;
        setTimeout(() => {
            fn.apply(this);
            console.log(this);
            // console.log(arguments);
            flag = true;
        }, time);
    }
}
function sayhi(e){
    console.log("hello li");
    console.log(e);  // undefined
}

let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));

加上arguments后

function throttle(fn,time){
   let flag = true;
   return function(){
       if(!flag) return;
       flag = false;
       setTimeout(() => {
           fn.apply(this,arguments);
           console.log(this);
           flag = true;
       }, time);
   }
}
function sayhi(e){
   console.log("hello li");
   console.log(e);  //
}

let box = document.getElementById('box');
box.addEventListener('click',throttle(sayhi,2000));
image.png

应用场景:

debounce
频繁操作点赞和取消点赞,因此需要获取最后一次操作结果并发送给服务器
throttle
鼠标不断点击触发,mousedown(单位时间内只触发一次)
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用节流来让其只触发一次

上一篇 下一篇

猜你喜欢

热点阅读