Only Bolivian Here
Only Bolivian Here

Reputation: 36753

How can I decrease the value of an HTML element each second using jQuery?

Here's what I have so far:

var timer = setInterval(function () {
    $(".auctiondiv .auctiondivleftcontainer .countdown").text(sec--);
}, 1000);

This works fine, but the problem arises because I have to set the value of sec on startup and every countdown element on my page has the same value. So instead of saving the value and decreasing that, maybe it's best to just get the value each tick and decrease it - without saving the value anywhere in Javascript.

How can I grab the text inside of the .countdown element (a <p> tag) and subract one from it and assign it back to the same <p> element? What has me confused is that there are many .countdown elements on my page, how would I go through each one?

I also need to make sure that a .countdown value once it reaches zero, I can do something. A conditional so to speak. I imagine I can use .parent() on it, but we'll see.

Any guidance?

Upvotes: 0

Views: 1249

Answers (2)

Jose Faeti
Jose Faeti

Reputation: 12304

You should store the elements you use more than once in a variable to save resources.

Also, the used of setTimeout is encouraged over setInterval due to a difference in their behavior. You can read why here.

// cache elements to save resources
var $countdownElements = $( ".countdown" );

function countDown() {

    $countdownElements.each( function () {
        var $this = $( this ); // again, cache element for later use
        var newValue = parseInt( $this.text(), 10 ) - 1;
        $this.text( newValue );
        if ( newValue == 0 ) {
           //Do something
        }
    });

    // call this function again in 1 second
    setTimeout( countDown, 1000 );
}

countDown();

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

You can use the jQuery each method to iterate over the matched set of elements:

var timer = setInterval(function () {
    $(".countdown").each(function() {
        var newValue = parseInt($(this).text(), 10) - 1;
        $(this).text(newValue);
        if(newValue == 0) {
           //Do something
        }
    });
}, 1000);

I've changed the selector to just .countdown because you said you have many such elements on the page, and I'm assuming they're not all going to be matched by your original selector, but you can obviously change that as necessary.

Here's a working example of the above code.

Upvotes: 3

Related Questions