zoukankan      html  css  js  c++  java
  • Javascript 代理模式模拟一个文件同步功能

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Document</title>
    </head>
    <body>
    	<input type="checkbox" id="1">
    	<input type="checkbox" id="2">
    	<input type="checkbox" id="3">
    	<input type="checkbox" id="4">
    	<input type="checkbox" id="5">
    	<input type="checkbox" id="6">
    	<input type="checkbox" id="7">
    	<input type="checkbox" id="8">
    	<input type="checkbox" id="9">
    	<input type="checkbox" id="10">
    	<p id="status"></p>
    <script>
    	var checkbox = document.getElementsByTagName('input');
    
    	//本体类,同步逻辑处理
    	var syncFile = function(id){
    		//Ajax等同步代码...
    		document.getElementById('status').innerHTML = '正在同步文件'+id;
    	}
    
    	//代理类,通过一个闭包结构保存cache和timer
    	var syncFileProxy = (function(){
    		var cache = [];
    		var timer = null;
    
    		return function(id){
    			cache.push(id);
    			//小于2秒的同步请求,则不会处理
    			if(timer){
    				return;
    			}
    			timer = setTimeout(function(){
    				syncFile(cache.join(','));
    				clearTimeout(timer); //清除定时器
    				timer = null; //重置变量
    				cache = []; //重置cache数组
    			},2000);
    		}
    	})();
    
    	for(var i = 0; i < checkbox.length; i++){
    		checkbox[i].onclick = function(){
    			if(this.checked === true){
    				syncFileProxy(this.id);
    				//可以随时替换成 syncFile(this.id)
    			}
    		}
    	}
    </script>
    </body>
    </html>
    
  • 相关阅读:
    flask全栈开发3 模板
    flask全栈开发2 URL与视图
    flask全栈开发1 课程简介
    微信公众号开发中遇到的问题总结
    python web学习路线
    内存数据库Memcached和redis基本使用
    2019年8月12号成长题目
    2019年8月10号成长题目
    2019年8月7号成长题目
    SpringCloud简介与5大常用组件
  • 原文地址:https://www.cnblogs.com/jaychan/p/5978277.html
Copyright © 2011-2022 走看看