Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防抖函数 #12

Open
conan1992 opened this issue Jun 10, 2020 · 0 comments
Open

防抖函数 #12

conan1992 opened this issue Jun 10, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

防抖

原理:你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内不再触发事件,才执行;

实现

function debounce(fn, timeout){
	timeout = timeout || 200;
	var timer = null;
	return function(){
		clearTimeout(timer);
		timer = setTimeout(fn, timeout)
	}
}

完善-this指向

function debounce(fn, timeout){
	timeout = timeout || 200;
	var timer = null;
	return function(){
		clearTimeout(timer);
		timer = setTimeout(fn.bind(this), timeout)
	}
}

完善-参数传递

function debounce(fn, timeout){
	timeout = timeout || 200;
	var timer = null;
	
	return function(){
		var context = this;
		var args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function(){
			fn.apply(context, args)
		}, timeout)
	}
}

需求--立即执行

事件触发后立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。

function debounce(fn, timeout, immediate){
	timeout = timeout || 200;
	var timer = null;
	return function(){
		var context = this;
		var args = arguments;
		clearTimeout(timer);
		if(immediate){
			var callNow = !timer;
			if(callNow){
				fn.apply(context, args)
			}
			timer = setTimeout(function(){
				timer = null;
			}, timeout)
		}else{
			
			timer = setTimeout(function(){
				fn.apply(context, args)
			}, timeout)
		}
		
	}
} 

返回值

function debounce(fn, timeout, immediate){
	timeout = timeout || 200;
	var timer = null;
	var result;
	return function(){
		var context = this;
		var args = arguments;
		clearTimeout(timer);
		if(immediate){
			var callNow = !timer;
			if(callNow){
				result = fn.apply(context, args)
			}
			timer = setTimeout(function(){
				timer = null;
			}, timeout)
		}else{
			
			timer = setTimeout(function(){
				fn.apply(context, args)
			}, timeout)
		}
		return result;
	}
} 

取消

function debounce(fn, timeout, immediate){
	timeout = timeout || 200;
	var timer = null;
	var result;
	var debounced =  function(){
		var context = this;
		var args = arguments;
		clearTimeout(timer);
		if(immediate){
			var callNow = !timer;
			if(callNow){
				result = fn.apply(context, args)
			}
			timer = setTimeout(function(){
				timer = null;
			}, timeout)
		}else{
			
			timer = setTimeout(function(){
				fn.apply(context, args)
			}, timeout)
		}
		return result;
	}
	debounced.cancel = function(){
		clearTimeout(timer);
		timer = null;
	}
}  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant