Reputation: 178
I am having a problem of resetting an elapsed time using setInterval function. The timer runs well when pressing start and stopping it by clicking a button. But when I click start button again the timer resumes instead of reset. Based on my research ,clearInterval would reset that but doesn't work.
Here's a sample of my code. https://jsfiddle.net/4165y1x4/16/
HTML
<button id="get_data">Fetch Data</button>
<button id="stop1">Stop</button>
<span id="run-time"></span>
<br>
Javascript
var start = new Date().getTime(),elapsed = '0.0';
var s , url,i=0, time;
$("#get_data").click(function() {
s = setInterval(function() {
$("#run-time").html(tym());
}, 100);
});
$('#stop1').click(function() {
clearInterval(s);
time = null;
});
function tym() {
$("#run-time").html('');
time = new Date().getTime() - start;
var min = (time / 1000 / 60) << 0;
var sec = (time / 1000) % 60;
if (sec < 10) {
sec = '0' + sec;
}
return elapsed = 'Elapsed Time: ' + min + ':' + sec + ' (min:sec.mil).'
}
I hope someone could help. Best Regards!
Upvotes: 0
Views: 115
Reputation: 1065
yeah at Rayon comment correctly, you have to restart the time again.JsFiddle
var start,
elapsed = '0.0';
var s , url,i=0, time;
$("#get_data").click(function() {
start = new Date().getTime();
s = setInterval(function() {
$("#run-time").html(tym());
}, 100);
// getData();
});
$('#stop1').click(function() {
clearInterval(s);
time = null;
});
function tym() {
$("#run-time").html('');
time = new Date().getTime() - start;
var min = (time / 1000 / 60) << 0;
var sec = (time / 1000) % 60;
if (sec < 10) {
sec = '0' + sec;
}
return elapsed = 'Elapsed Time: ' + min + ':' + sec + ' (min:sec.mil).'
}
Upvotes: 0