javascript实现在一定时间段内相同请求之执行一次

方法一:(此方法是建立在假设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>
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值