问答详情
源自:8-3 计时器setInterval()

求大神帮我看看这个代码出什么问题了(添加stop和start按钮控制计时开始和结束)

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>定时器</title>
<script type="text/javascript">
  var attime;
  function clock(){
      
    var time=new Date();          
    attime=time.getHours()+":"+time.getMinutes()+":"+time.getSeconds() ;
    document.getElementById("clock").value = attime;
  }
  function startclock(){
      var i=setInterval("clock()",1000);
  }
  function stopclock(){
     clearInterval(i);
  }
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50"  />
<input type="button" id="start" value="start" onclick="startclock()" />
<input type="button" id="stop" value="stop"  onclick="stopclock()"/>
</form>
</body>
</html>

start可以开始但是stop停止不了为啥啊--

提问者:sololdw 2015-05-16 17:25

个回答

  • 全障攻城师
    2015-05-16 17:45:31
    已采纳

    把 var i=setInterval("clock()",1000);中的var去掉

  • ITer在路上
    2015-07-14 14:52:33

    函数变量作用域的问题啊,那个i的作用域范围在startclock函数内,你想在stopclock函数里去访问i,这样肯定访问不到啊!