<script>
      var s=0;
 var timeId   ;
 timeId=setInterval("count();",1);//定义定时器 返回TIMEID  每隔1秒钟执行一次COUNT()函数, function  count() 
 {
     document.getElementById("set").innerHTML= s++;   //获取ID SET当中的所有HTML文本(这里是一个数值
 }
function  stop()
  {
  clearInterval(timeId);   // 关闭定时器
   }
  </script>
<form>
<font id="begin" onclick="count()" > 计时开始:&nbsp;<font>
<font id="set"  color="red" style="font-size:30px" >0</font>  秒
<input type="button"    onclick ="stop()" value="stop"/>
</form>
问题是:当  timeId定义为全局变量时,无法STOP;而当定义为count的局部变量时,无法结束,要如何改进呢

解决方案 »

  1.   

    当 timeId定义为全局变量时,无法STOP;可以Stop啊
      

  2.   

    <script>
      var s=0;
    var timeId ;
    //定义定时器 返回TIMEID 每隔1秒钟执行一次COUNT()函数, function count()  
    {
      document.getElementById("set").innerHTML= s++; //获取ID SET当中的所有HTML文本(这里是一个数值
    }
    function run(){
        timeId=setInterval(function(){count()},1000);
    }
    function stop()
    {
    clearInterval(timeId); // 关闭定时器
    }
      </script><input type="button" onclick="run()" value="计时开始"/>
    <font id="set" color="red" style="font-size:30px" >0</font> 秒
    <input type="button" onclick="stop()" value="stop"/>
      

  3.   

    2楼果然有用。将计时和ONCLICK事件分开了,这样更清楚。