抖动和节流

抖动和节流

<input id="search" type="text"/>
<div id="content" style="height: 150px;line-height: 150px; text-align: center;background-color: gray;"></div>
	<script>
        let num = 1;
        function count(){
            content.innerHTML = num++
        }
        document.getElementById('search').oninput = count()
        document.getElementById('content').onmousemove = count()
	</script>

抖动

方式一:让输入完毕后过1秒再查询

function debounce(func, wait){
	let timeout;
	return function(){
		if(timeout) clearInterval(timeout)
			timeout = setTimeout(() => {
				func.apply(this)
			},wait)
	}
}

方式二:输入完毕立即查询,过2秒才能再查询

function debounce(func, wait){
	let timeout;
	return function(){
		if(timeout) clearTimeout(timeout)
		let callNow = !timeout
        timeout = setTimeout(() => {
        	timeout = null;
        },wait)
        if(callNow) func.apply(this)
	}
}

节流(固定的时间去发请求)

        // 定时器 
        function throttle(func, wait){
        	let timeout
        	return function(){
        		if(!timeout){
        			timeout = setTimeout(() => {
        				timeout = null
        				func.apply(this)
        			},wait)
        		}
        	}
        }
        // 时间戳
        function throttle(func, wait){
            let prev = 0
            return function(){
                let now = Date.now()
                if(now - prev > wait){
                    func.apply(this)
                    prev = now
                }
            }
        }
发布了34 篇原创文章 · 获赞 0 · 访问量 616

猜你喜欢

转载自blog.csdn.net/qq_44631273/article/details/104456660