`
ihuashao
  • 浏览: 4514967 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

在javascript中用command模式模拟多线程

阅读更多

作者:emu(黄希彤)今天和徐鹏程msn的时候聊起javascript不支持多线程。以前也看过有高手在wsh上可以创建thread对象,但是毕竟不是常规手段,我们做web应用一般没有本地访问权限的,用activex的没试过,毕竟也不是javascript方式。

以前我们解决这样的问题都是针对具体问题写一段代码来模拟多线程的,但是由于往往要对没个线程单独编码,这样的代码十分冗长。学习设计模式的时候就曾经考虑过在javascript中实用command模式来更好的模拟多线程,但是一直没有付诸实施,今天既然想起来了就试试看:

1<html><head><title>emu--用command模式模拟多线程</title></head><body>
2<SCRIPTLANGUAGE="JavaScript">
3<!--
4if(Array.prototype.shift==null)
5Array.prototype.shift=function(){
6varrs=this[0];
7for(vari=1;i<this.length;i++)this[i-1]=this[i]
8this.length=this.length-1
9returnrs;
10}

11if(Array.prototype.push==null)
12Array.prototype.push=function(){
13for(vari=0;i<arguments.length;i++)this[this.length]=arguments[i];
14returnthis.length;
15}

16
17varcommandList=[];
18varnAction=0;//控制每次运行多少个动作
19varfunctionConstructor=function(){}.constructor;
20functionexecuteCommands(){
21for(vari=0;i<nAction;i++)
22if(commandList.length>0){
23varcommand=commandList.shift();
24if(command.constructor==functionConstructor)
25if(command.scheduleTime==null||newDate()-command.scheduleTime>0)
26command();
27else
28commandList.push(command);
29}

30}

31
32functionstartNewTask(){
33varresultTemp=document.getElementById("sampleResult").cloneNode(true);
34with(resultTemp){
35id="";style.display="block";style.color=(Math.floor(Math.random()*(1<<23)).toString(16)+"00000").substring(0,6);
36}

37document.body.insertBefore(resultTemp,document.body.lastChild);
38commandList.push(function(){simThread(resultTemp,1);});
39nAction++;
40}

41
42functionsimThread(temp,n){
43if(temp.stop)n--;
44elsetemp.innerHTML=temp.innerHTML-(-n);
45if(n<1000)
46commandList.push(function(){simThread(temp,++n)});
47else{
48varcommand=function(){document.body.removeChild(temp);;nAction--;};
49command.scheduleTime=newDate()-(-2000);
50commandList.push(command);
51}

52}

53
54window.onload=function(){setInterval("executeCommands()",1);}
55//-->
56
</SCRIPT>
57<buttononclick="startNewTask()">开始新线程</button>
58
59<BR><BR>
60<divid=sampleResultonmouseover="this.stop=true"onmouseout="this.stop=false"style="display:none;cursor:hand">0</div>
61</body>
62</html>

注意第26行。javascript里面函数也是对象,所以就没有必要把函数调用包装到do或者execute方法里面了,直接用()就可以让函数对象运行起来:
command();

shift和push函数是javascript中array对象的函数,可是IE5居然没有定义,最前面两个函数是为IE5准备的。

在IE和FireFox下面通过作者:emu(黄希彤)

点击这里看效果
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics