Simple AngularJs Countdown Timer

A Simple AngularJs Countdown Timer has come in handy a few times while making new products and slowly removing the dependency on jQuery. I originally wrote a countdown timer using jQuery, but with AngularJs that isn’t considered best practices. This is what the previous javascript looked like.

OLD WAY:

//Countdown timer starting at 3, then closes current window.
var _startCountdown = function(){
	var count = 3;
	var counter = setInterval(function () {
	count = count - 1;
	if (count <= 0) {
	  clearInterval(counter);
	  $('#timer').hide();
	  $('#success').show();
	  //Wait just a second then close tab.
	  setTimeout(function () {
		$window.close();
	  }, 1000);
	  return;
	}
	$('#timer').text(count);
	}, 900);
}

This worked fine and served its purpose. However, with wanting to removed jQuery from within the angular controller, I decided to find a way to do this solely in AngularJs. It turned out to be quite easy.

NEW WAY:

var _startCountdown = function(){
	var timerCount = 3;

	var countDown = function () {
		if (timerCount < 0) {
		  //Any desired function upon countdown end.
		  $window.close();
		} else {
		  $scope.countDownLeft = timerCount;
		  timerCount--;
		  $timeout(countDown, 1000);
		}
	};
	$scope.countDownLeft = timerCount;
	countDown();
}

Now, within your html you have access to a scope variable called {{ countDownLeft }}. Make sure to pass in $timeout into your controller.

StackOverflow Profile