防抖和节流—应用场景及实现

5 篇文章 0 订阅

防抖

  1. 概念
    假定时间间隔为200ms,如果触发事件后的200ms内再次触发事件,则重新等待200ms,否则将成功执行指定函数。

  2. 应用场景
    数据查询、监控用户输入

  3. 代码实现

    function search() {
    	var t = null; // 使用闭包
    	return function () {
    		if (t) {
    			clearTimeout(t);
    			t = null
    		}
    		t = setTimeout(() => {
    			console.log('执行啦');
    			t = null;
    		}, 2000);
    	}
    }
    var test1 = document.getElementById('test2');
    test1.onclick = search();
    

节流

  1. 概念
    连续触发事件,只在指定时间间隔执行指定函数。

  2. 应用场景
    页面自适应、监控页面滚动、鼠标移动

  3. 代码实现

    // 方法一:首次立即触发
    function throttle1(fn, interval) {
    	let open = true
    	let first = true
    	return function () {
    		if (!open) {
    			return
    		}
    		open = false
    		// !!!!!! 首次立刻执行
    		if (first) {
    			console.log('首次触发')
    			fn()
    			first = false
    		}
    		const now = Date.now()
    		const wait = now % interval
    		setTimeout(() => {
    			fn()
    			open = true
    		}, interval - wait)
    	}
    }
    
    // 方法二:首次立即触发,间隔时间更稳定
    function throttle2(fn, interval) {
    	let lastTime = 0
    	let timer = null
    	return function () {
    		const context = this
    		const args = arguments
    		const curTime = Date.now()
    		const duration = interval - (curTime - lastTime)
    		clearTimeout(timer)
    		if (duration <= 0) {
    			fn(args)
    			lastTime = curTime
    		} else {
    			timer = setTimeout(function () {
    				fn.apply(context, args)
    				lastTime = lastTime + interval
    			}, duration)
    		}
    	}
    }
    
    // 测试代码
    let times = 0
    let onMouseMove = throttle2(() => {
    	console.log(new Date().getTime(), times)
    }, 10)
    let i = setInterval(() => {
    	if (times++ === 1000) {
    		clearInterval(i)
    	}
    	onMouseMove()
    }, 1)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值