面试必备--防抖和节流

防抖(debounce)
原理

事件响应函数fn在一段时间后才执行,如果在这段内再时间再次调用,则重新计算执行时间,当预定的时间内没有再次调用该函数,则执行fn

实现
	function debounce (func, wait) {
        let timer = null;
        return function() {
            let _this = this;
            let args = arguments;
            if (timer) {
                clearTimeout(timer)
                timer = null
            }
            timer = setTimeout(function () {
                func.call(_this, ...args);
            }, wait)
        }
    }
注意细节
  • 函数中this的指向问题
  • 函数的参数如何获取
应用场景
  1. scroll事件滚动出发
  2. 搜索框输入查询
  3. 表单验证
  4. 按钮提交事件
  5. 浏览器窗口缩放等等
节流(throttle)
原理

频繁触发函数fn,每间隔一段时间执行函数fn

实现
  1. 时间戳的方式实现
    function throttle(func, time) {
    	let _this, args,
    	let initialTime = 0;
    	return function() {
    		_this = this;
    		args = arguments;
    		let currrentTime = new Date().getTime();
    		if(currrentTime - initialTime > time){
    			func.apply(_this, arguments);
    			initialTime = currrentTime
    		}
    	}
    }
    
  2. 通过定时器的方式实现
    function throttle(func, time) {
    	let _this;
    	let args;
    	let timer = null;
    	return function() {
    		_this = this;
    		args = arguments;
    		if(!timer) {
    			timer = null;
    			timer = setTimeout(() => {
    				func.call(_this, ...args)
    			}, time)
    		}
    	}
    }
    
应用场景
  1. Dom元素的拖拽
  2. 射击游戏
  3. 计算鼠标移动的距离
  4. 监听滚动条滚动事件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值