javascript 模拟多线程
2008-07-08 16:44:02
在javascript中,是没有线程的,只能模拟一个了,前些日子写了个,现在把它贴出来。 thread.js: /** * 线程管理类 * @author zxub 2006-06-12 */ function Thread(_task,_delay,_times) { this.runFlag=false; this.busyFlag=false; this.taskArgs=Array.prototype.slice.call(arguments,3); if (_times!=undefined) { this.times=_times; } else { this.times=1; } var _point=this; this.timerID=-1; this.start=function() { if (this.runFlag==false) { this.timerID=window.setInterval(_point.run,_delay); this.runFlag=true; } } this.run=function() { if (_point.busyFlag) return; if (_point.times==-1)//无限循环 { _task(_point.taskArgs); } else if (_point.times>0) { _task(_point.taskArgs); _point.times-=1; if (_point.times==0) { window.clearInterval(this.timerID); } } } this.sleep=function() { this.busyFlag=true; } this.resume=function() { this.busyFlag=false; } this.abort=function() { window.clearInterval(this.timerID); } } 例子如下: <html> <head> <title>测试</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="thread.js"></script> <style type="text/css"> <!-- body,tr,td { font-size: 12px;} --> </style> </head> <body> <script> var func=function(_o) { document.getElementById(_o).innerHTML=parseInt(document.getElementById(_o).innerHTML)+1; } var t1=new Thread(func,50,121,"t1"); var t2=new Thread(func,200,20,"t2"); </script> <input type="button" value="start1" onclick='t1.start();'></input> <input type="button" value="sleep1" onclick='t1.sleep();'></input> <input type="button" value="resume1" onclick='t1.resume();'></input> <input type="button" value="abort1" onclick='t1.abort();'></input> <input type="button" value="start2" onclick='t2.start();'></input> <input type="button" value="sleep2" onclick='t2.sleep();'></input> <input type="button" value="resume2" onclick='t2.resume();'></input> <input type="button" value="abort2" onclick='t2.abort();'></input> <div id="t1">0</div> | <div id="t2">0</div> <input type="button" value="t1.timerID" onclick='alert(t1.timerID);'></input> <input type="button" value="t2.timerID" onclick='alert(t2.timerID);'></input> </body> </html> 本文出自 51CTO.COM技术博客 |


xu20cn
博客统计信息
热门文章
最新评论
友情链接