日期:2014-05-16  浏览次数:20393 次

真正的js异步执行队列
需要用到一个选择模型角度后,等待250ms的渲染,然后拍照的功能。网上找了找,类似sleep的功能,基本上都是死循环,跳出(还有一些加入时间比较啥的,其实一点用都没有,没有出让cpu,比不比时间没有差别),这种代码一执行,基本上浏览器都会告诉你,脚本执行缓慢,是否取消。唯一的办法,就是用setTimeout模拟。没办法,只能自己写了,很简陋,但功能已具备,有需要可以加以扩展。
var ExecQueue = function() {
	this.queue = [];
};
ExecQueue.prototype = {
	add : function(fn, args, time) {
		this.queue.push( {
			fn : fn,
			args : args,
			time : time
		});
	},
	exec : function() {
		var delay = 0;
		for ( var i = 0; i < this.queue.length; i++) {
			var _this=this;
			var f=function(idx){
				return function(){
				_this.queue[idx].fn.apply(_this,_this.queue[idx].args);
				}
			}(i);
			setTimeout(f, delay);
			delay += this.queue[i].time;
		}
	}
}

function a(){
	alert('a');
}
function b(i){
	alert('b'+i);
}
function c(i,j){
	alert('c'+i+j);
}
var execqueue=new ExecQueue();
execqueue.add(a,[],5000);
execqueue.add(b,['i'],5000);
execqueue.add(c,['c1','c2'],5000);
execqueue.add(c,['c3','c4'],2000);
execqueue.exec();
1 楼 dong87 2011-04-06  
您好,当我用如下代码测试的时候,发现程序进入了死循环,不知该如何解决
var execqueue=new ExecQueue(),counter = 0; 
function doWork() {
document.write("<br/><br/>新一轮执行:<br/>");
for (var i=1; i<=3; i++) execqueue.add(writeSth,[i],500);
if (counter++ < 3) execqueue.add(doWork,[],1000);
execqueue.exec();
}
function writeSth(theWord) {
document.write(theWord + "<br/>");
}
doWork();
2 楼 dong87 2011-04-06  
发现是执行新一轮操作的时候没有清空列队导致的
每次执行doWork()时候先清空一下可以解决,但不够优雅,求优雅点的解决方案

function doWork() {
execqueue.queue = []; // <---------加上这句就好了
document.write("<br/><br/>新一轮执行:<br/>");
for (var i=1; i<=3; i++) execqueue.add(writeSth,[i],500);
if (counter++ < 3) execqueue.add(doWork,[],1000);
execqueue.exec();
}
3 楼 dong87 2011-04-06  
用我的发放解决之后发现doWork()的执行间隔无法控制,不是按设定的1000执行的,好像是按前面的500执行的
4 楼 teclogid 2011-04-15  
dong87 写道
用我的发放解决之后发现doWork()的执行间隔无法控制,不是按设定的1000执行的,好像是按前面的500执行的

这个异步队列是最简单的情形,不支持动态的add,如果执行过程中,需要动态add,需要修改一下add方法