Try this way . In any case, stopwatch takes into account hundredths of a second.
var count = 3000; var counter = setInterval(timer, 10); //10 will run it every 100th of a second function timer() { if (count <= 0) { clearInterval(counter); return; } count--; document.getElementById("timer").innerHTML=count /100+ " secs"; }
Just for better formatting and testing :
HTML
<span id="timer"></span> <button id="start">start</button> <button id="stop">stop</button> <button id="reset">reset</button>
Javascript
var initial = 30000; var count = initial; var counter; //10 will run it every 100th of a second function timer() { if (count <= 0) { clearInterval(counter); return; } count--; displayCount(count); } function displayCount(count) { var res = count / 100; document.getElementById("timer").innerHTML = res.toPrecision(count.toString().length) + " secs"; } $('#start').on('click', function () { clearInterval(counter); counter = setInterval(timer, 10); }); $('#stop').on('click', function () { clearInterval(counter); }); $('#reset').on('click', function () { clearInterval(counter); count = initial; displayCount(count); }); displayCount(initial);
EDIT:
The initial question was trying to figure out how to make a display like a stopwatch, and I know very little that actually counts milliseconds. However, here is a possible solution for this. He relies on the update as quickly as possible and gets the difference between our last update and our current one to stay accurate.
var initial = 300000; var count = initial; var counter; //10 will run it every 100th of a second var initialMillis; function timer() { if (count <= 0) { clearInterval(counter); return; } var current = Date.now(); count = count - (current - initialMillis); initialMillis = current; displayCount(count); } function displayCount(count) { var res = count / 1000; document.getElementById("timer").innerHTML = res.toPrecision(count.toString().length) + " secs"; } $('#start').on('click', function () { clearInterval(counter); initialMillis = Date.now(); counter = setInterval(timer, 1); }); $('#stop').on('click', function () { clearInterval(counter); }); $('#reset').on('click', function () { clearInterval(counter); count = initial; displayCount(count); }); displayCount(initial);
MirroredFate
source share