原帖子發表在 http://community.csdn.net/Expert/TopicView.asp?id=4069144
有csdn的朋友把http://community.csdn.net/Expert/TopicView.asp?id=3191873 給翻了出來,這樣在javascript中模擬多線程又有了更漂亮的做法了:
在IE6和firefox1.5下面通過
有的時候command模式也許不是最好的辦法,比如我之前寫的例子。寫那個例子純粹只是為了演示command確實可以用在javascript中,并不表示我們任何時候都應該優先考慮這樣做。 至于command模式本身,我仍認為它是最簡潔優美的模式之一,在我們用各種語言解決問題的時候都可以考慮使用它,而不止于j2se。 套一句名言:如果你的工具箱里面只有榔頭這一樣工具,那么每個問題在你的眼里看起來都象釘子 。
有csdn的朋友把http://community.csdn.net/Expert/TopicView.asp?id=3191873 給翻了出來,這樣在javascript中模擬多線程又有了更漂亮的做法了:
1
<html><head><title>emu -- 用fason的參數化定時器模擬多線程</title></head><body>
2
<SCRIPT LANGUAGE="JavaScript">
3
<!--
4
5
var _st = window.setTimeout;
6
window.setTimeout = function(fRef, mDelay)
{
7
if(typeof fRef == 'function')
{
8
var argu = Array.prototype.slice.call(arguments,2);
9
var f = (function()
{ fRef.apply(null, argu); });
10
return _st(f, mDelay);
11
}
12
return _st(fRef,mDelay);
13
}
14
15
var _int = window.setInterval;
16
window.setInterval = function(fRef, mDelay)
{
17
if(typeof fRef == 'function')
{
18
var argu = Array.prototype.slice.call(arguments,2);
19
var f = (function()
{ fRef.apply(null, argu); });
20
return _int(f, mDelay);
21
}
22
return _st(fRef,mDelay);
23
}
24
25
26
function startNewTask()
{
27
var target = document.getElementById("sampleResult").cloneNode(true);
28
with (target)
{
29
id="";style.display="block";style.color=(Math.floor(Math.random()* (1<<23)).toString(16)+"00000").substring(0,6);
30
}
31
document.body.insertBefore(target,document.body.lastChild);
32
var parameter =
{target:target,n:0,result:0}
33
parameter.timer = setInterval(count,1,parameter);
34
}
35
36
function count(parameter)
{
37
with (parameter)
{
38
if (!target.stop)
{
39
for(var i=0;i<speed;i++)
40
if (n<MAX) result += ++n;
41
target.innerHTML = result;
42
}
43
if (n>=MAX)
{
44
clearInterval(timer);
45
setTimeout(function(elm)
{document.body.removeChild(elm)},2000,target);
46
}
47
}
48
}
49
50
var speed = 1111;
51
var MAX=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>

2



3

4

5

6



7



8

9



10

11

12

13

14

15

16



17



18

19



20

21

22

23

24

25

26



27

28



29

30

31

32



33

34

35

36



37



38



39

40

41

42

43



44

45



46

47

48

49

50

51

52

53

54

55

56

57

58

59

在IE6和firefox1.5下面通過
有的時候command模式也許不是最好的辦法,比如我之前寫的例子。寫那個例子純粹只是為了演示command確實可以用在javascript中,并不表示我們任何時候都應該優先考慮這樣做。 至于command模式本身,我仍認為它是最簡潔優美的模式之一,在我們用各種語言解決問題的時候都可以考慮使用它,而不止于j2se。 套一句名言:如果你的工具箱里面只有榔頭這一樣工具,那么每個問題在你的眼里看起來都象釘子 。