Kifsif
Kifsif

Reputation: 3843

Timer shows wrong results

var seconds_lapsed = 0;

function tick() {    
    seconds_lapsed++;
}

function countup() { 
    setTimeout(function () {
        if (stopped) return; // stop the loop
        if (!is_paused()) {
            tick();
            show_time_left();            
        }
        countup(); // <--- this is the "loop"
    }, 1000);
}

This is the core of my timer. Of course I have some view to represent the result. But ticking is done here.

The problem

It shows wrong time. Have a look at this:

enter image description here

The timer was set for 3 hours. Twelve minutes lapsed. And the discrepancy is almost 1.5 minutes.

In the other window the timer by Google is working. This one:

enter image description here

So, I just compared my timer with that of google. I started them almost at once. The difference should be no more than a couple of seconds (to switch the window and press the button).

What is the reason for this, and how can I correct it?

Upvotes: 1

Views: 105

Answers (1)

Kevin Verstraete
Kevin Verstraete

Reputation: 1453

setTimeout with an interval of 1000 does NOT run exactly after every 1 seconds. It schedules to run after 1 second, but can be delayed with by actions running at that time.

A better way of solving this is by calculating via date difference. I took your sample (added the missing vars/funcs) and changed the tick() function to use date diffs.

var seconds_lapsed = 0;
var startDateTime = new Date();
var stopped = false;
var is_paused = function() { return false; }

function tick() {    
    datediffInms =  new Date() - startDateTime;
    seconds_lapsed = Math.round(datediffInms / 1000);
}

function countup() { 
    setTimeout(function () {
        if (stopped) return; // stop the loop
        if (!is_paused()) {
            tick();
            //show_time_left();            
            console.log(seconds_lapsed)
        }
        countup(); // <--- this is the "loop"
    }, 1000);
}


countup();

Upvotes: 2

Related Questions