wepli23
wepli23

Reputation: 87

How to loop a function in Javascript?

I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.

I try to do this with the JQuery countdown plugin:

var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
    var goal = date + " " + time[i];
    $("#countdown")
        .countdown(goal, function(event) {
            if (event.elapsed) {
                i++;
            } else {
                $(this).text(
                    event.strftime('%H:%M:%S')
                );
            }
    });
}

This does not work... But how can i do this?

Upvotes: 2

Views: 66

Answers (3)

thedude
thedude

Reputation: 9822

You should never use a busy wait especially not in the browser.

Try something like this:

var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
    var goal = date + " " + time[i];
    $counter.countdown(goal, function(event) {
        if (event.elapsed) {
            i++;
            if (i < time.length) {
              countdown();
            }
        } else {
            $(this).text(
                event.strftime('%H:%M:%S')
            );
        }
    });
}

Upvotes: 1

DoctorMick
DoctorMick

Reputation: 6793

You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.

var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];

function startCountdown(i) {
    if(i >= i.length) {
        return;
    }

    var goal = date + " " + time[i];

    $("#countdown")
        .countdown(goal, function(event) {
            if (event.elapsed) {
                startCountdown(i++);
            } else {
                $(this).text(
                    event.strftime('%H:%M:%S')
                );
            }
    });
}

startCountdown(0);

Upvotes: 1

dfsq
dfsq

Reputation: 193301

You can't use while or for loop in this case, because the operation you want to perform is not synchronous.

You could do for example something like this with the helper (anonynous) function:

var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;

(function countdown(i) {
  if (i === time.length) return;


  var goal = date + " " + time[i];
  $("#countdown")
    .countdown(goal, function(event) {
      if (event.elapsed) {
        countdown(i++);
      } else {
        $(this).text(event.strftime('%H:%M:%S'));
      }
    }); 
})(0)

Upvotes: 1

Related Questions