现在的位置: 首页 > 综合 > 正文

javascript中的线程之我见

2013年10月17日 ⁄ 综合 ⁄ 共 2260字 ⁄ 字号 评论关闭

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
 </head>

 <body>
   <script type="text/javascript">
/**
 * 线程管理类
 * @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);        
    }
}
 
   </script>

   <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>

抱歉!评论已关闭.