1

I am encountering a problem where the delay of window.setTimeout() seems to be ignored or randomized.

function timer() {
    var refreshTimer = 0;

    var delay = 300000; // 5 min

    this.init = function () {
        this.startRefreshTimer();
        $(document)
            .ajaxStop(this.startRefreshTimer)
            .ajaxStart(this.stopRefreshTimer)
        ;
    };

    this.startRefreshTimer = function() {
        refreshTimer = window.setTimeout(resetTimer, delay - 10000);
    };

    this.stopRefreshTimer = function() {
        window.clearTimeout(refreshTimer);
    };

    function resetTimer() {
        $.ajax(url);
    }

    this.init();
}

This works for a random set of times (and even in multiple browsers and tabs) but after a while the delay breaks out.

Here's also a log of the request times:

17:50:04
17:54:55 // + 5 min - ~10 sec
17:59:46 // ||
18:04:37 // ||
18:09:28 // ||
18:14:19 // ||
18:19:10 // ||
18:24:01 // ||
18:28:52 // ||
18:33:43 // ||
18:38:34 // ||
18:43:25 // ||
18:48:16 // ||
18:53:07 // ||
18:57:58 // ||
19:15:09 // + ~ 17 min ???

I cannot use window.setInterval() and i will not give any more information about the purspose of this code. I simply want to know if someone has made similar experiences and/or knows of a solution for this problem.

user1506674
  • 131
  • 1
  • 5
  • There is a slight delay with setTimeout and it will never be 100% accurate. setInterval is more accurate but still not 100% the only thing i can suggest, is work out the ammount of miliseconds you are out of target, and then add that to the next `setTimeout` – rorypicko Sep 04 '13 at 12:07
  • [1] http://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout [2] http://www.sitepoint.com/creating-accurate-timers-in-javascript/ – Cristi Pufu Sep 04 '13 at 12:32
  • @Cristi: THX a lot. Links really helped understanding the matter. Although some references are kinda deprecated and / or too wannebe js ninja like. Anyway, problem solved for me. If anybody cares i would take the time to post my solution. – user1506674 Sep 05 '13 at 05:57

0 Answers0