JSFiddle - React, Tailwind, and code Playground
by prozoroff
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl as myCtrl">
<div>
Status: {{status ? status : 'Waiting...'}}
</div>
<div>
<button ng-click="myCtrl.addTimer(5)">Add timer</button>
</div>
<div ng-repeat="timer in myCtrl.timers">
<div>
<h3>Timer {{::timer.id}}</h3>
<button ng-click="myCtrl.removeTimer($index)">X</button>
<my-timer start-seconds="timer.seconds" on-finish="status = 'Timer ' + timer.id + ' finished at ' + $endTime"></my-timer>
</div>
</div>
</div>
JavaScript
angular.module('myApp', []).controller('MyCtrl', class {
constructor($scope) {
this.timerId = 0;
this.timers = [];
this.addTimer(10);
this.addTimer(3);
this.scope = $scope;
}
addTimer(seconds) {
const timer = {
id: this.timerId++,
seconds,
};
this.timers.push(timer);
this.startTimer(timer);
}
startTimer(timer) {
const ctrl = this;
var id = setInterval(() => {
ctrl.scope.$apply(function() {
timer.seconds -= 1;
if (timer.seconds === 0) {
ctrl.removeTimer(timer.id);
clearInterval(id);
}
})
}, 1)
}
removeTimer(index) {
this.timers.splice(index, 1);
}
}).component('myTimer', {
controller:'MyCtrl',
bindings: {
startSeconds: '<',
onFinish: '&?',
},
template: `<span>{{$ctrl.startSeconds}}</span>`,
});