JS中的防抖和节流

在前端开发中,经常会遇到频繁触发某一事件的情况,如 scroll、mousemove、onchange等。这种高频率的触发会造成卡顿等现象。
解决这种问题通常有两种方法:防抖节流

防抖 debounce

防抖原理:事件触发 n 秒后才执行,如果在一个事件触发的 n 秒内又触发了这个事件,以新的事件的时间为准,n 秒后才执行。总之,就是要触发完事件 n 秒内不再触发事件。

01.png

html

 <input type="text" id="inp" />

基础版本:

function debounce(func, delay) {
    var timer;   //计时器id
    return function () {
        clearTimeout(timer)  //清除计时器
        timer = setTimeout(func, delay);
    }
}
// 调用
inp.oninput = debounce(function(){console.log("test"),1000)

好了,一个基础的防抖函数就完成了。
但这样写有两个问题没有解决:this指向event对象

this

//如果输出this, 指向window
inp.oninput = debounce(function(){console.log(this),1000)

event

function debounce(func, delay) {
    var timer;   //计时器id
    return function () {
        clearTimeout(timer)  //清除计时器
        timer= setTimeout(func, delay);
    }
}
function bing(e) {
    console.log(e)
}
// 调用
inp.oninput = debounce(bing, 1000)
//输出 undefined

完善后的代码

function debounce(func, delay) {
    var timer;   //计时器id
    return function () {
        let _this = this;   //保留this
        let _arg = arguments; //保留event
 
        clearTimeout(timer)  //清除计时器
        timer = setTimeout(function(){
            func.apply(_this,_arg)   //改变指向
        }, delay);
    }
}
function bing(e) {
    console.log(e,this.value)
}
// 调用
inp.oninput = debounce(bing, 1000)

节流 throttle

节流原理 :特定的时间内周期,事件只会执行一次,不管被触发了多少次。
如一些抽奖系统等。

02.png

节流的实现目前有两种主流方式:时间戳定时器

HTML

<span id='show'>0</span>
<button id="ibox">click</button>

script

   //节流
    let show = document.querySelector('#show'),
        ibox = document.querySelector('#ibox')

    function throttle(fn, wait) {//shell函数
        let lastTime = 0
        return function (e) {
            let nowTime = new Date().getTime()
            if (nowTime - lastTime > wait) {
                fn.apply(this, arguments)
                lastTime = nowTime
            }
        }
    }
    function buy(e) {
        show.innerText = parseInt(show.innerText) + 1
    }
    ibox.onclick = throttle(buy, 1000)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在前端开发的过程中,我们经常会需要绑定一些持续触发的事件,如 resize、scroll、mousemove 等等...
    Grace_feb3阅读 403评论 0 0
  • 前言 最近和前端的小伙伴们,在讨论面试题的时候。谈到了函数防抖和函数节流的应用场景和原理。于是,想深入研究一下两者...
    youthcity阅读 23,701评论 5 78
  • 在前端开发的过程中,我们经常会需要绑定一些持续触发的事件,如 resize、scroll、mousemove 等等...
    淘淘笙悦阅读 226,735评论 42 349
  • 转自 简书 什么是函数防抖和节流 在前端开发过程中,我们经常会遇到需要绑定一些持续性出发事件的场景.例如resiz...
    TouchMe丶阅读 428评论 1 0
  • 在前端开发的过程中,我们经常会需要绑定一些持续触发的事件,如 resize、scroll、mousemove 等等...
    meng_281e阅读 198评论 1 0