改变HTML输入会搞乱我的JS setInterval()时序

时间:2016-06-30 19:05:45

标签: javascript jquery input setinterval

使用JSBin:https://jsbin.com/nijozefoma/

我有一个带有setInterval()框和输入框的页面。要复制问题,请尝试加载下面的代码,在框中手动键入4.5而不是0,然后单击下面的文本。然后,将其更改为9.5。文本应该每1秒计算一次,但由于某种原因,它对我来说要快得多。

思想?

<head>

<!-- CSS inclusion -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

</head>
<body>
Input Box: <input type="number" class="timeSelect workSelect" value=0 /> 
<div class="startButton">
    Change the input to 4.5, and click this text. Then change to 9.5, and click again.
</div>
<div class="secondCounter">
</div>
<!-- Javascript Inclusion -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript">

var  secondsPassed;
function startTime(){
  secondsPassed = 0 ;
  $(".secondCounter").html("secondsPassed is "+ secondsPassed);
}
function updateTime(){
  secondsPassed ++;
  $(".secondCounter").html("secondsPassed is "+ secondsPassed);
}

$(".startButton").click(function(){
  startTime();
  setInterval(updateTime, 1000);
})

</script>

</body> 

2 个答案:

答案 0 :(得分:3)

$(".startButton").click(function(){
  startTime();
  setInterval(updateTime, 1000);
})

每次点击startButton时,您都会启动另一个间隔,这意味着updateTime会运行两次。

取消旧间隔或更新代码,以便setInterval不会启动两次。

答案 1 :(得分:1)

每次都需要清除计时器

<script type="text/javascript">

var timer,
    secondsPassed;

function startTime(){
  secondsPassed = 0 ;
  $(".secondCounter").html("secondsPassed is "+ secondsPassed);
}

function updateTime(){
  secondsPassed ++;
  $(".secondCounter").html("secondsPassed is "+ secondsPassed);
}

$(".startButton").click(function(){
  startTime();
  if(timer) clearInterval(timer);
  timer = setInterval(updateTime, 1000);
})

</script>

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval