Search code examples
javascripttimerionic-frameworkmobile-website

Why is there a delay in java script timer?


I am trying to use java script and ionic to build hybrid mobile web app. I have a timer functionality where you click on the start button and timer should start.

Here is someone's js fiddle example http://jsfiddle.net/AbrGL/

function startClock() {
    if (clicked === false) {
        clock = setInterval("stopWatch()", 1000);
        clicked = true;
    }
    else if (clicked === true) {
    }
}

When you click on start button, we have a slight delay (like 1 second) before the counter starts.

Is there a way to make this faster ?


Solution

  • You can reduce the 1000 milliseconds parameter to zero, or some really low number. The caveat here is that some browsers have a minimum of 10 or 20 milliseconds when firing intervals so there may be glitches, overlapping and other unintended results.

    You can also add in a maximum number of times the interval fires as well for additional control.

    clock = setInterval("stopWatch()", 20, 2);
    

    The clock variable will now repeat every 20 milliseconds for a total of 2 times.