函数防抖和函数节流

96 阅读1分钟

1.函数防抖

概念:函数防抖是一个延时器,阻断连续重复的函数调用,从而一定程度上优化性能。

用途:主要用于用户界面dom操作的函数,比如onclick,keyup事件。

var processor = {
	timeoutId: null,
	performProcessing: function ( ) {        //实际进行处理的方法
		//实际执行的代码
	},
	//初始处理调用的方法
	process: function( ) {
		clearTimeout(this.timeoutId);    //清除1s内未执行的定时器任务
		var _this = this;
		this.timeoutId = setTimeout(function( ) {
			_this. performProcessing();
		}, 1000);
	}
} 
processor. process();



function fn(callback,deleteTime) {
    let timer;
    return function() {
        clearTimeout(timer);
        console.log('----111',this)
        console.log('----222',arguments)
        const that = this;
        const arg = arguments;
        timer = setTimeout(() => {
            callback.apply(that, arg)
        }, deleteTime)
    }()
}
fn(fn1, 2000)
const fn1 = function(){
    
}

2.函数节流

概念:当持续触发事件时,保证在一定时间内只调用一次事件处理函数。

var obj = {
    timeout: null,
    result: function() {
        new promise(() => {})
    },
    process: function() {
       var _this = this;
        this.timeout = setInterval(() => {
             _this.result();
        }, 1000)
    }
}
obj.process();