maxum
maxum

Reputation: 2915

Add time to javascript clock

I want to be able to add a specified time to a javascript clock and have it keep updating. I have managed to chuck the below together.

    function leadTimer(leadTime) 
    {
      var d1 = new Date (),
      d2 = new Date ( d1 );
      d2.setMinutes ( d1.getMinutes() + leadTime );
      currentHours = d2.getHours();
      currentMins = d2.getMinutes();
      // Choose either "AM" or "PM" as appropriate
      var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
      // Convert the hours component to 12-hour format if needed
      currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
      // Convert an hours component of "0" to "12"
      currentHours = ( currentHours == 0 ) ? 12 : currentHours;
      if (currentMins<=9) { currentMins="0"+currentMins; }
      if (currentHours<10) { currentHours="0"+currentHours; }
      $("#result").empty();
      $("#result").html(currentHours + ":" + currentMins + " " + timeOfDay)
      setInterval('leadTimer(leadTime)',10000)
}

I figured that the setInterval would just use the current value for leadTime but I just get an error saying leadTime is undefined.

Ultimately I would like to be able to call on this to keep a clock ticking over depending on what the user selects.

Upvotes: 2

Views: 426

Answers (1)

maerics
maerics

Reputation: 156394

You've almost got it; the preferred way to use setInterval is to give it a function as the first argument, so try changing your last line to this instead:

setInterval(function(){leadTimer(leadTime)}, 10000);

Upvotes: 5

Related Questions