Page 1 of 1
[SOLVED] JavaScript » Exact seconds increment
Posted: Mon Feb 04, 2008 7:49 pm
by Jonah Bron
Hello, world!
There is a javascript issue in my current project. It requires a timer of sorts, but after testing, I found that setTimeout is not entirely precise. It is not necessarily the same as the time, but must move in sync with the seconds of the time. Have been working on this, but haven't figured anything out.
Thanks!
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 12:46 am
by devendra-m
Code: Select all
var seconds=60;
var timeInMilliseconds = seconds * 1000;
window.setTimeout('function_name()',timeInMilliseconds);
I hope I meant what you want
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 9:26 am
by Kieran Huggins
I think what you're probably looking for is setTimeout()'s less popular brother: setInterval().
A lot of people instinctively try to emulate setInterval() by re-setting setTimeout() in the callback, but there will always be inherent time loss while the callback is running.
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 9:50 am
by Jonah Bron
Thanks, devendra-m. That's what is inaccurate. I tested it over the span of several hours, and it eventually got off track.
I'll google setInterval. Thanks!
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 12:07 pm
by Jonah Bron
Okay,
Tested setInterval, and at one second, it loses one second every minute. So, I reduced it to 998, and it lost 3 seconds every 10 minutes. So, I reduced it again, to 997 milliseconds, and am testing...
Loses 1 second every 10 minutes. Taking one millisecond...
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 12:51 pm
by arjan.top
There is no guarantee that it will behave the same in other browser etc.
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 1:05 pm
by Kieran Huggins
I'd use a Date() object to track the time, using setInterval() to update the display only.
The Date() object will just report the system time, so it should be accurate.
Re: JavaScript » Exact seconds increment
Posted: Tue Feb 05, 2008 2:22 pm
by Jonah Bron
Thanks, arjan.top. That's just what I was thinking...
You see, great minds think alike! That what I did:
Code: Select all
var pl = false;
var hrs = 0;
var mins = 0;
var secs = 0;
var count = 0;
var lastTime = 0;
function startCount(){
if (secs==59){
secs = 0;
if (mins==59){
mins = 0;
hrs++;
}else{
mins++;
}
}else{
secs++;
}
document.getElementById('hrs').value = hrs;
document.getElementById('mins').value = mins;
document.getElementById('secs').value = secs;
}
function getT(){
var myTime = new Date().getSeconds();
if (lastTime!=myTime){
startCount();
lastTime = myTime;
}
}
When you click the "start" button, it sets an interval for getT() at 1/10/sec, which calls "startCount()" if the second has changed. The pause button calls the "clearInterval" function.
Thanks everyone!