zoukankan      html  css  js  c++  java
  • 用fason的参数化定时器在javascript中模拟多线程

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

    有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
     5var _st = window.setTimeout;
     6window.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
    15var _int = window.setInterval;
    16window.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
    26function 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
    36function  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
    50var speed = 1111;
    51var 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>


    有的时候command模式也许不是最好的办法,比如我之前写的例子。写那个例子纯粹只是为了演示command确实可以用在javascript中,并不表示我们任何时候都应该优先考虑这样做。 至于command模式本身,我仍认为它是最简洁优美的模式之一,在我们用各种语言解决问题的时候都可以考虑使用它,而不止于j2se。 套一句名言:如果你的工具箱里面只有榔头这一样工具,那么每个问题在你的眼里看起来都象钉子author:emu(黄希彤)
  • 相关阅读:
    找最后的字符
    统计指定数字和
    班级排队
    python编程题
    python函数题
    2019.6.24-2019.6.28(实训数据结构)3.数组编码求解问题
    2019.6.24-2019.6.28(实训数据结构)1.商品管理系统实训c++(实现的基本功能:初始化,创建表,插入,删除,更新,查询,链表数据与文件之间的转换)
    2019.6.24-2019.6.28(实训数据结构) 2.背包问题
    2019.6.24-2019.6.28(实训数据结构)4.树和二叉树应用项目
    2019.6.24-2019.6.28(实训数据结构)5.图的邻接矩阵表示
  • 原文地址:https://www.cnblogs.com/stonehuang/p/6603231.html
Copyright © 2011-2022 走看看