<!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>