防抖和节流 简单易懂

防抖:通过setTimeout 的方式,在一定时间间隔内,将多次触发变为一次触发

用户触发事件过于频繁,只执行最后一次

// 1.先获取dom节点
	var ipt = document.getElementById("input")
	// 2.定义一个清空定时器的变量
	var t = null
	// 3.触发事件
	ipt.oninput = function () {
		// 4.判断有没有t
		if (t !== null) {
			// 5.如过有就清除定时器
			clearTimeout(t)
		}
		// 6.如果没有t就把定时器赋值给t
		t = setTimeout(() => {
			console.log(this.value);
		}, 1000)
	}

这样就实现了,在一秒的间隔内,多次点击就会清除定时器,间隔超出一秒后就会执行定时器

封装一下:

// 1.先获取dom节点
	var ipt = document.getElementById("input")

	ipt.oninput = debounce(function () {
		console.log(this.value);
	}, 1000)

	// 封装一个防抖
	function debounce(fn, time) {
		var t = null
		return function () {
			if (t !== null) {
				clearTimeout(t)
			}
			t = setTimeout(() => {
				// 需要使用call改变this指向,不然this指向window
				fn.call(this)
			}, time)
		}
	}

节流:控制执行次数

控制高频事件的执行次数

  // 节流
        window.onscroll = throttle(function () {
            console.log("1");
        }, 500)
        function throttle(fn, time) {
            let flag = true;
            return function () {
                if (flag) {
                    setTimeout(() => {
                        fn()
                        // 每次定时器执行之后都把flag改为true
                        flag = true
                    }, time);
                }
                flag = false
            }
        }

猜你喜欢

转载自blog.csdn.net/weixin_53150999/article/details/122909342