palAlaa
palAlaa

Reputation: 9838

jQuery delay inside loops

I want to make a timer in jQuery, I want change the value of span each second I make like this, but it delay is not working.

 function startTimer(daysRemain,hoursRemain,minutesRemain,secondsRemain){

            while(secondsRemain < 60){
               secondsRemain++;
               $("span.secondRemain").delay(1000).text(secondsRemain);  //change value of seconds each one second 
                // I try this way too!
               /* setTimeout(function(){
                    $("span.secondRemain").text(secondsRemain);
                },1000);*/

            }

Upvotes: 2

Views: 10925

Answers (3)

uadnal
uadnal

Reputation: 11425

delay is only for the fx queue.

A standard timer is as follows

var t = 0;
setInterval(function () {
    $('div').text(t);
    t += 1;
},1000);

http://jsfiddle.net/J9Zwa/

Upvotes: 6

Andreas Wong
Andreas Wong

Reputation: 60506

Have you tried:

setInterval(function(){
   $("span.secondRemain").text(secondsRemain);
},1000);

Upvotes: 1

jfriend00
jfriend00

Reputation: 707158

.delay() doesn't delay your running javascript. It goes into the animation queue and when the queue gets to that operation, it sets a timer for the delay time and doesn't proceed to the next operation in the queue until that much time has elapsed.

As such, you can't use it in your loop to make a javascript delay. You will need to use setTimeout() like this.

function startTimer(daysRemain,hoursRemain,minutesRemain,secondsRemain) {

     function nextTime() {
         if (secondsRemain < 60){
             secondsRemain++;
             $("span.secondRemain").text(secondsRemain);  //change value of seconds each one second 
             setTimeout(nextTime, 1000);
         }
     }
     nextTime();
}

Upvotes: 1

Related Questions