zoukankan      html  css  js  c++  java
  • 防抖与节流

    <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>
    
    
  • 相关阅读:
    HDU 4388 To the moon
    HDU 4757 Tree
    HDU 5816 Hearthstone
    hihocoder 1356 分隔相同整数
    HDU 5726 GCD
    POJ3026 Borg Maze(Prim)(BFS)
    POJ1258 Agri-Net(Prim)
    POJ1751 Highways(Prim)
    POJ2349 Arctic Network(Prim)
    POJ1789 Truck History(Prim)
  • 原文地址:https://www.cnblogs.com/lajiao/p/9759166.html
Copyright © 2011-2022 走看看