Reputation: 135
I am using the below to count milliseconds, it works perfectly well. But I want to call a logout() when the timer value is 9 seconds. It does not work. Can you anyone suggest ?
</script>
<script type="text/javascript">
var timer, time = 0, start_time = 0;
function startstoptimer()
{
if (timer)
{
time += new Date().getTime() - start_time;
start_time = 0;
clearInterval(timer);
timer = null;
}
else
{
start_time = new Date().getTime();
timer = setInterval(function ()
{
document.d.d2.value = (time + new Date().getTime() - start_time)/1000;
if((time + new Date().getTime() - start_time)/1000==9.000)
logout();
}, 10);
}
}
</script>
<script>
function logout()
{
alert('Time is up');
}
</script>
Upvotes: 0
Views: 122
Reputation: 11935
Beware of unprecise floating point number comparisons, you cannot predict if the comparison can fail due truncation/precision errors caused by floating point arithmetics, I would avoid trust that
This is what I would do:
function startstoptimer()
{
if (timer)
{
time += new Date().getTime() - start_time;
start_time = 0;
clearInterval(timer);
clearTimeout(launchLogoutTimer); // clear timeout
timer = null;
}
else
{
start_time = new Date().getTime();
timer = setInterval(function ()
{
document.d.d2.value = (time + new Date().getTime() - start_time)/1000;
/*if((time + new Date().getTime() - start_time)/1000==9.000)
logout();// dont call logout here */
}, 10);
// this way, you will be sure logout will be called after 9 seconds
// (unless you cancel it before using clearTimeout)
launchLogoutTimer = setTimeout(logout, 9000);
}
}
Upvotes: 1