Skip to content

防抖与节流 #44

@chenhuiYj

Description

@chenhuiYj

防抖:触发高频事件后 n 秒内函数只会执行一次,如果 n 秒内高频事件再次被触发,则重新计算时间。作用:防止事件连续或高频触发,让它只触发一次或者最后一次。

function debounce (fn, delay){
	let timer=null
	return function(){
		if(timer){
			clearTimeout(timer)
		}
		timer=setTimeout(()=>{
			fn.apply(this,arguments)
			timer=null
		},delay)
	}
}

let test=debounce(()=>{console.log(1)},5000)

节流:高频事件触发,但在 n 秒内只会执行一次,所以节流会稀释函数的执行频率。作用:降低事件触发的频率,比如2s 内最多执行一次。

function throttle(fn, wait){
	let last=0
	return function(){
		let now=+new Date()
		if(now-last>=wait){
			fn.apply(this,arguments)
			last=now
		}
	}
}

let test=throttle(()=>{console.log(2)},2000)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions