JSFiddle - React, Tailwind, and code Playground
by Jeremy Likness
HTML
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<div ng-app="myApp" ng-controller="myController as ctrl">
<button ng-click="ctrl.startTimer()">Start</button>
<div ng-show="ctrl.isRunning">Running</div>
<div ng-hide="ctrl.isRunning">Stopped</div>
</div>
JavaScript
function ExternalTimer (config) {
this.timeout = config.timeoutSeconds || 5;
this.callback = config.timerCallback || function () {};
};
ExternalTimer.prototype.tick = function () {
var _this = this;
setTimeout(function () {
_this._ticks += 1;
console.log('tick' + _this._ticks);
if (_this._ticks < _this.timeout) {
_this.tick();
}
_this.callback(_this.timeout - _this._ticks);
}, 1000);
};
ExternalTimer.prototype.start = function () {
console.log('start');
this._ticks = 0;
this.tick();
};
(function () {
var app = angular.module('myApp', []);
function Controller ($scope) {
this.isRunning = false;
this.apply = function (expr) {
$scope.$apply(expr);
};
};
Controller.$inject = ['$scope'];
Controller.prototype.startTimer = function () {
console.log('startTimer');
var _this = this,
timer = new ExternalTimer({
timeoutSeconds: 3,
timerCallback: function (remaining) {
if (remaining === 0) {
_this.apply(function () {
_this.isRunning = false;
});
}
}
});
timer.start();
this.isRunning = true;
};
app.controller('myController', Controller);
})();