用fason的参数化定时器在javascript中模拟多线程

博客介绍了在JavaScript中模拟多线程的更漂亮做法,给出了相关代码示例,包括对`setTimeout`和`setInterval`函数的重写以实现参数化定时器模拟多线程。此外,还提到command模式并非在任何时候都是最佳选择,但它仍是简洁优美的模式之一。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原帖子发表在 http://community.youkuaiyun.com/Expert/TopicView.asp?id=4069144 author:emu(黄希彤)

有csdn的朋友把 http://community.youkuaiyun.com/Expert/TopicView.asp?id=3191873给翻了出来,这样在javascript中模拟多线程又有了更漂亮的做法了:

1 < html >< head >< title > emu--用fason的参数化定时器模拟多线程 </ title ></ head >< body >
2 < SCRIPT LANGUAGE ="JavaScript" >
3<!--
4
5var_st=window.setTimeout;
6window.setTimeout=function(fRef,mDelay){
7if(typeoffRef=='function'){
8varargu=Array.prototype.slice.call(arguments,2);
9varf=(function(){fRef.apply(null,argu);});
10return_st(f,mDelay);
11}

12return_st(fRef,mDelay);
13}

14
15var_int=window.setInterval;
16window.setInterval=function(fRef,mDelay){
17if(typeoffRef=='function'){
18varargu=Array.prototype.slice.call(arguments,2);
19varf=(function(){fRef.apply(null,argu);});
20return_int(f,mDelay);
21}

22return_st(fRef,mDelay);
23}

24
25
26functionstartNewTask(){
27vartarget=document.getElementById("sampleResult").cloneNode(true);
28with(target){
29id="";style.display="block";style.color=(Math.floor(Math.random()*(1<<23)).toString(16)+"00000").substring(0,6);
30}

31document.body.insertBefore(target,document.body.lastChild);
32varparameter={target:target,n:0,result:0}
33parameter.timer=setInterval(count,1,parameter);
34}

35
36functioncount(parameter){
37with(parameter){
38if(!target.stop){
39for(vari=0;i<speed;i++)
40if(n<MAX)result+=++n;
41target.innerHTML=result;
42}

43if(n>=MAX){
44clearInterval(timer);
45setTimeout(function(elm){document.body.removeChild(elm)},2000,target);
46}

47}

48}

49
50varspeed=1111;
51varMAX=100000;
52//-->
53
</ SCRIPT >
54 < button onclick ="startNewTask()" > 开始新线程 </ button >
55
56 < BR >< BR >
57 < div id =sampleResult onmouseover ="this.stop=true" onmouseout ="this.stop=false" style ="display:none;cursor:hand" > 0 </ div >
58 </ body >
59 </ html >


有的时候command模式也许不是最好的办法,比如我之前写的例子。写那个例子纯粹只是为了演示command确实可以用在javascript中,并不表示我们任何时候都应该优先考虑这样做。 至于command模式本身,我仍认为它是最简洁优美的模式之一,在我们用各种语言解决问题的时候都可以考虑使用它,而不止于j2se。 套一句名言:如果你的工具箱里面只有榔头这一样工具,那么每个问题在你的眼里看起来都象钉子 author:emu(黄希彤)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值