garson garson - 5 months ago 15
jQuery Question

Altering HTML input is messing up my JS setInterval() timing

Working JSBin: https://jsbin.com/nijozefoma/

I have a page with a setInterval() box and an input box. To duplicate the problem, try loading the code below, manually type 4.5 instead of 0 in the box, and click the text below. Then, change it to 9.5. The text should count up every 1 second, but for some reason it's going much faster for me.

Thoughts?

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

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

Every time you hit the startButton you start another interval which means that updateTime is then run twice.

Either cancel the old interval or update your code so that setInterval isn't started twice.

Comments