JS 防抖与节流

防抖: 连续事件不触发, 停了0.5s才触发
记忆: 如果没有防抖,输入一个字发送一次请求, 浏览器会卡顿, 所以叫防抖

let t=null
ipt.oninput = function(){
	if(t !== null)
		clrTimeOut(t)  //在0.5s以内的都清掉了
	t = setTimeOut(function fn(){} , 500)  //只有最后一次达到0.5s,才执行一次fn()
}

节流: 连续事件每隔0.5s触发一次

let flag = true
ipt.oninput = function(){
	if(flag)
		setTimeOut(function fn(){ flag=true } , 500)  //只有最后一次达到0.5s,才执行一次fn()
	flag = false
}

区别:
比如有一个连续触发10s的事件, 防抖只触发第10s的事件, 节流在10s内每0.5s触发一次事件

节流使用:

import throttle from 'lodash/throttle';//节流  throttle节流阀
import debounce from 'lodash/debounce';//防抖  bounce反弹  debounce防止反弹
methods: {

    changeIndex: throttle(function (index) {
      this.currentIndex = index;
    }, 20),
		
	...
	
	getFullName: debounce(function() {
      console.log('my fullname is chentingjun')
	}, 500),
		
posted @ 2022-02-23 22:54  波吉国王  阅读(28)  评论(0编辑  收藏  举报