Question

I have problem with setTimeout.

In all major browsers it works fine but not in IE... I'm creating a facebook app- puzzle. When player press Start button, the timer starts count his time of playing one game. At the beginning I used setInterval to increase timer but with cooperate of facebook scripts it delayed about 2 seconds at the end of game. Then I found on stackoverflow trick to increase accuracy of timer: setInterval timing slowly drifts away from staying accurate And again- without facebook it worked fine, no delays were shown. With facebook it still has delays. Now to condensate info that might interest You: When user clicks Start then I create new Date as startTime. When user ends game script creates finalTime new Date, then substract finalTime - startTime.

In code there is setTimeout:

(...)    

f : function() {
        var sec_time = Math.floor((puzzle.nextAt - puzzle.startTime)/1000);
        $('.timer').html(sec_time);
        if (!puzzle.startTime) {
            puzzle.startTime = new Date().getTime();
            puzzle.nextAt = puzzle.startTime;
            $('.timer').html('0');
        }
        puzzle.nextAt += 100;
        puzzle.to = setTimeout(puzzle.f, puzzle.nextAt - new Date().getTime());
    }

(...)    

when user place on correct place last puzzle piece then I call clearTimeout(puzzle.to);

I have now 2 issues:

  1. not accurate time, in IE it can be even 7 second difference!

  2. in IE during game it works only when user have mousedown... :/

To drag puzzles I use jQuery drag & drop plugin. At least very helpful info will be how to achieve accurate timer.

Was it helpful?

Solution

You should put your scripts in jQuery's ready function and not at the bottom of the page, as the Facebook SDK is loaded asynchronously and may impact timed executions if they're initiated at the bottom of the page.

As for timing, you're gonna see inaccuracy of between 15ms and 45ms in IE7 depending on other JS executions on the page. Your 100ms timeout will drift badly because of this. Better to record a start time and build a timer with a higher polling frequency than needed and do a comparison between start time and 'now' in each cycle to determine what to do next.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top