1

I have a question: When I do a countdown in JavaScript, and I have a function of the form:

        <script>
var interval;
var minutes = 1;
var seconds = 5;
window.onload = function() {
    countdown('countdown');
}

function countdown(element) {
    interval = setInterval(function() {
        var el = document.getElementById(element);
        if(seconds == 0) {
            if(minutes == 0) {
                el.innerHTML = "countdown's over!";                    
                clearInterval(interval);
                return;
            } else {
                minutes--;
                seconds = 60;
            }
        }
        if(minutes > 0) {
            var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
        } else {
            var minute_text = '';
        }
        var second_text = seconds > 1 ? 'seconds' : 'second';
        el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
        seconds--;
    }, 1000);
}
</script>

The time between each one performance of the function is exactly 1 sec. or there is some delay caused by time due to perform body of function?

user1827257
  • 1,600
  • 4
  • 17
  • 24

2 Answers2

1

No, setTimeout() and setInterval() have impredictable accuracy, as said in this other question you can get better precision by setting a timeout once and than using (new Date()).milliseconds to do time related actions instead of using setTimeout() for every thing

Community
  • 1
  • 1
Polyana Fontes
  • 3,156
  • 1
  • 27
  • 41
0

There are functions setTimeout(fnc, delay) and setTimeout(fnc, delay) that are said to call fnc after at least delay ms. See MDN for details.

Artem Sobolev
  • 5,891
  • 1
  • 22
  • 40