节流防抖

理解:
节流:事件频繁触发,设置一个周期,事件每一个周期触发一次
防抖:事件频繁触发,只有最后一次生效

—————————————————————————

节流场景:
1.窗口调整(resize)
2.页面滚动(scroll)
3.拖拽功能
4.按钮疯狂点击
防抖场景
1.搜索联想
2.文本输入验证:(连续输入文字发送ajax,只验证最后一次)
3.判断scroll是否滑动到顶部/底部

—————————————————————————

// 点击事件的回调
function handleClick() {
	console.log("点击事件")
}

// 实现节流的函数
function throttle(callback, delay) {
	let start = 0;		// 保证第一次点击立即调用
	return function() {	// 它的this是谁就要让callback()中的this是谁,它接受所有的实参都直接交给callback()
		const current = Date.now()
		if(current - start > delay) {
			callback.apply(this, arguments)
			start = current
		}
	} 
}
document.getElementById("throttle").onClick = throttle(handleClick, 1000)

// 实现防抖的函数

function debounce(callback, delay) {
	return function() {
		const self = this;
		const args = arguments;
		// 清除待执行的定时器任务
		if(callback.timeoutId) {
			clearTimeout(callback.timeoutId)
		}
		// 每隔delay的时间,启动一个新的延时定时器,去准备调用callback
		callback.timeoutId = setTimeout(() => {
			callback.apply(self, args)
			// 如果回调完成,删除定时器
			delete callback.timeoutId
		}, delay)
	}
}
document.getElementById("debounce").onClick = debounce(handleClick, 1000)

防抖(debounce)

// js代码
test = () => {
    if (this.timer) {
        clearTimeout(this.timer);
        this.timer = 0
    }

    this.timer = setTimeout(() => {
        this.timer = 0

        // 需要做防抖的操作
        console.log(1)

    }, 500);
}

// 组件代码
<button onClick ={this.test.bind(this)} >
    防抖测试
</button>
  
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值