你不重视的JS基础 - 函数节流与函数防抖

113 阅读1分钟

函数节流与函数防抖的区别

1.相同点

函数节流与函数防抖都是可以防止一个函数被无意义的高频次使用

2.不同点

函数节流:确保函数在特定的时间内至多被执行一次。

函数防抖:函数在特定时间内不被再调用后执行

3.JS代码实现

函数节流:相比于函数防抖,函数节流就是让函数在特定的时间内只执行一次。

var canRun = true;
document.getElementById("throttle").onscroll = function() {
	if (!canRun) {
    	return;
    }
    canRun = false;
    setTimeout(function(){
    	console.log("函数被节流了");
        canTrue = true;
    }, 1000)
}

函数防抖:在规定时间内,函数只能被调用一次,不能被频繁多次调用。

function throlle(method, context) {
  clearTimeout(method.timer);
  method.timer = setTimeout(function() {
    method.call(context)
  }, 1000)
}

function run() {
  console.log('resize')
}

window.onresize = throlle(run, window)