LoyalKnight LoyalKnight - 5 months ago 112
AngularJS Question

Getting Time Left (Countdown) -- Html, Javascript, AngularJS

Basically, I'm trying to build a spaceship launch app that pulls data from say, a spreadsheet, and displays the time left for each spacecraft's launch. BTW, I did look at the (few) questions on Stack right now about getting time left, but they don't seem very comprehensive and I'm confused on how to implement them into my code.

Here's a snippet from my html:

<h2>Rocket Launch: {{launch.name}}</h2>
<p>Time left: x minutes</p>
<script>
var currentdate = new Date();
var datetime = (currentdate.getMonth()+1) + "/" + currentdate.getDate() + "/"
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
</script>


As you can see, I'm using angularJS's $scope to get the launch's name in line 1. Then I'm trying to display the time left until the launch...but I'm kind of unsure how to do so? In the script part starting in line 3, I found out how to display the Current time/date, but how am I supposed to be able to display the time remaining (launchtime - currenttime) in the HTML? I'm kind of confused and would like a few pointers to guide me.

By the way, I'm just starting out in AngularJS and hoping to put something somewhat simple yet meaningful together. Sorry about pretty much being a newb.

Thanks

Answer

I took a few minutes to write up a countdown algorithm

$scope.CountDown = {
    getTimeRemaining: function(endtime) {
      var t = Date.parse(endtime) - Date.parse(new Date());
      var seconds = Math.floor((t / 1000) % 60);
      var minutes = Math.floor((t / 1000 / 60) % 60);
      var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
      var days = Math.floor(t / (1000 * 60 * 60 * 24));
      return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
      };
    },

    initializeClock: function(endtime) {
      function updateClock() {
        var t = $scope.CountDown.getTimeRemaining(endtime);

        $scope.CountDown.days = t.days;
        $scope.CountDown.hours = ('0' + t.hours).slice(-2);
        $scope.CountDown.minutes = ('0' + t.minutes).slice(-2);
        $scope.CountDown.seconds = ('0' + t.seconds).slice(-2);

        if (t.total <= 0) {
          $interval.cancel(timeinterval);
        }
      }

      updateClock();
      var timeinterval = $interval(updateClock, 1000);
    }
}

All you have to do is add the CountDown object to your scope and call $scope.CountDown.initializeClock($scope.launch.date);

I made a plunker here https://plnkr.co/edit/x0BkVPgPLjD8rtbfADtY?p=preview

You can display CountDown.days, CountDown.hours, CountDown.minutes and CountDown.seconds on your html view

Comments