Search code examples
javascriptjquerycountdown

simple multiple second countdown


I have several <span class="timer">342</span> with different values (seconds). I want to countdown all of them and thought I could do something like:

            $('.timer').ready(function() {
                timer = setInterval(function() {
                    sec = $('.timer').text();
                    $('.timer').text(--sec);
                    if (sec == 0) {
                        clearInterval(timer);
                        location.href = 'accounts.php';
                    }
                }, 1000);
            });

The error is, Javascript gets confused because of more than 1 object of .timer or something and generates weird values for the spans.

When the first timer hits zero it should reload. Using jQuery. The number of spans is not fixed. I'd really like to keep it simple and don't use an extra plugin or big script file.


Solution

  • .ready is only used for the document and marks the point when the DOM is fully parsed. Within this function, this refers to the document. I'd write it another way:

    $(document).ready(function() {
    
        timer = setInterval(function() {
            $('.timer').each(function(){
                var $this = $(this);
                var countdown = parseInt($this.text()) - 1;
    
                $this.text(countdown);
                if (countdown == 0) {
                    clearInterval(timer);
                    location.href = 'accounts.php';
                }
            });
        }, 1000);
    });
    

    Important:

    1. Use .each to iterate through every timer
    2. Use parseInt to get an integer from a string

    Here's an Example-Fiddle that works.