防抖与节流

<html>
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#container{
			height: 200px;
			400px;
			background-color: black;
			color: white;
			text-align: center;
			line-height: 200px;
			font-size: 18px;
		}
	</style>
</head>
<body>
	<div id="container"></div>

	<script>
		var count = 0;
		var container = document.getElementById('container');
		function getAction(){
			console.log(this);
			container.innerHTML = count++;
		}
		container.onmousemove = debounce(getAction, 1000, false);
		// container.onmousemove = throttle(getAction,1000);


// 防抖 true进来+1,false停止加1
		function debounce(func, wait, flag){
			var timeout;
			return function(){
				var myself = this;
				clearTimeout(timeout);
				if(flag){
					var callBow = !timeout;
					timeout = setTimeout(function(){
						timeout = null;
					}, wait);
					if(callBow){

						func.apply(myself);
					}
				}else{
					timeout = setTimeout(function(){
						func.apply(myself); //对象冒充
					}, wait)
				}
			}
		}	

/// 节流
		function throttle(func, wait){
			var myself;
			var previous = 0;
			return function(){
				var now = +new Date(); // === new Date().getTime();
				myself = this;
				if(now - previous > wait){
					func.apply(myself); //对象冒充
					previous = now;		
				}
			}
		}

	</script>
</body>
</html>

原文地址:https://www.cnblogs.com/lajiao/p/9759166.html