方法一:(此方法是建立在假设javascript的执行存在并发性的情况,并假设uuid获得一定是唯一的id)
/** 利用Array的push本身具有次序,最后肯定只有一个对象在首位 */
function Delayer(callback,delayTime){
this.callback = callback;
this.count = 0;
this.delayTime = delayTime;
this.queue = new Array();
this.ring = 0;
}
/* 此方法为UUID实现摘自网络 */
Delayer.prototype.getUniqueId = function(){
var s = [], itoh = '0123456789ABCDEF';
// Make array of random hex digits. The UUID only has 32 digits in it, but we
// allocate an extra items to make room for the '-'s we'll be inserting.
for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10);
// Conform to RFC-4122, section 4.4
s[14] = 4; // Set 4 high bits of time_high field to version
s[19] = (s[19] & 0x3) | 0x8; // Specify 2 high bits of clock sequence
// Convert to hex chars
for (var i = 0; i <36; i++) s[i] = itoh[s[i]];
// Insert '-'s
s[8] = s[13] = s[18] = s[23] = '-';
return s.join('')+'-'+(++this.ring); //通过ring更加提高唯一性
}
Delayer.prototype.delay = function(){
//减少后来者进入
if (this.count == 0) {
++this.count;
var uniqueId=this.getUniqueId();
this.queue.push(uniqueId);
//通过判断第一push进去的id是否是自己来决定是否执行
if (this.queue[0] == uniqueId) {
var self=this;
setTimeout(function(){
try{self.callback();}catch(err){}
//执行完后将值清空,保证下次还能执行
finally{
self.count = 0;
self.queue = new Array();
if(self.ring > 9999) self.ring = 0;
}
},this.delayTime);
}
}
}
方法二:(更为简洁,不过是以假设++variable的值一定不会相同为前提)
function Delayer(callback,delayTime){
this.callback = callback;
this.count = 0;
this.delayTime = delayTime;
}
Delayer.prototype.delay = function(){
if(++this.count==1){
var self=this;
setTimeout(function(){
try{self.callback();}catch(err){}
//执行完后将值清空,保证下次还能执行
finally{
self.count = 0;
}
},this.delayTime);
}
}
执行代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
</body>
<script type="text/javascript" src="Delayer.js"></script>
<script type="text/javascript">
function sayHello(){alert('hello')}
var sayHelloDelayer = new Delayer(sayHello,100);
sayHelloDelayer.delay();
sayHelloDelayer.delay();
sayHelloDelayer.delay();
sayHelloDelayer.delay();
sayHelloDelayer.delay();
</script>
</html>
本文介绍了一种使用JavaScript实现的任务延时执行器,通过两种不同的方法确保在多次调用时只执行一次回调函数,有效避免短时间内重复触发同一事件。
1146

被折叠的 条评论
为什么被折叠?



