Мне нужна функция таймера секундомера, написанная в угловом2 для моего онлайн-экзамена. Он должен отображаться в формате ЧЧ: ММ: СС. Она должна начинаться с 01:00:00 и должен заканчиваться в 00:00:00счетчик таймера функция в угловомJS 2
ответ
Вы можете сделать это следующим образом:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<button (click)="buttonClicked()">{{ started ? 'reset' : 'start' }}</button>
<br />
<span>{{ time.getHours() }}</span>:
<span>{{ time.getMinutes() }}</span>:
<span>{{ time.getSeconds() }}</span>
</div>
`,
})
export class App {
name:string;
started = false;
time = new Date(2000, 1, 1, 1, 0, 0);
constructor() {
this.name = 'Angular2'
this._timerTick();
}
private _timerTick() {
if (this.started) {
this.time.setSeconds(this.time.getSeconds(), -1);
}
setTimeout(() => this._timerTick(), 1000);
}
buttonClicked() {
if (this.started) this.reset();
else this.start();
}
start() {
this.started = true;
}
reset() {
this.started = false;
this.time = new Date(2000, 1, 1, 1, 0, 0);
}
}
демо: https://plnkr.co/edit/BkMkAuSoqVgQMhqEKAAg?p=preview
Но есть, как всегда, несколько способов достижения цели! :)
Большое вам спасибо. –
принимайте как ответ PLS, если это помогает :) – mxii
Html кнопка элемент, на котором функция таймера обратного отсчета получает срабатывает ...
<div class="form-group col-sm-3" [ngClass]="{'red':activate, 'white':!activate, 'blink_me':blink}"><i class="fa fa-clock-o" aria-hidden="true"></i> Time Left: <span>{{currentHour}}:{{currentMinute}}:{{currentSeconds}}</span></div>
<button class="btn btn-primary btn-sm" (click)="_timerTick()">Start Timer</button>
Полная функция таймера обратного отсчета идет здесь ниже код (Пожалуйста включить этот кусок кода в вашем классе компонентов таймера)
constructor(
private examService: ExamService,
private resultService: ResultService,
private activatedRoute: ActivatedRoute,
private route: Router) {
this.start(); //here our countdown timer function gets called by setting the boolean variable **this.started** as true.
}
start() {
this.started = true;
}
private _timerTick() {
if (this.started) {
if (localStorage.getItem('sec')) { // here it checks, if browser local-storage has key **sec** recorded. Basically, when browser gets refreshed by user on that case it used to store key **sec** in local-storage and continue countdown ticking without starting from the beginning.
this.time = new Date(localStorage.getItem('sec'));
this.time.setSeconds(this.time.getSeconds(), -1);
}
else {
this.time = new Date(2017, 2, 24, 0, 0, this.timeInSeconds);
this.time.setSeconds(this.time.getSeconds(), -1);
}
if (this.time.getHours() === 0 && this.time.getMinutes() === 0 && this.time.getSeconds() === 0) {
localStorage.removeItem('sec');
this.started = false;
this.saveData('Time Over!');
}
this.currentHour = this.time.getHours();
this.currentHour = ("0" + this.currentHour).slice(-2); //Here it check for two digits. If it is single then it adds 0 as prefix to it.
this.currentMinute = this.time.getMinutes();
this.currentMinute = ("0" + this.currentMinute).slice(-2);//Here it check for two digits. If it is single then it adds 0 as prefix to it.
this.currentSeconds = this.time.getSeconds();
this.currentSeconds = ("0" + this.currentSeconds).slice(-2);//Here it check for two digits. If it is single then it adds 0 as prefix to it.
if (this.currentHour == 0 && this.currentMinute < 5) {// This line states, if only 5minutes left out then timer get started blinking. Blink code given in below **css** code section
this.activate = true;
this.blink = true;
}
if (this.currentHour == 0 && this.currentMinute == 0 && this.currentSeconds == 0) {// If time is up then we would remove complete browser cache using below lines of code and also deactivate the timer blinking.
localStorage.removeItem('sec');
localStorage.setItem('examTaken', this.name);
this.activate = false;
this.blink = false;
}
else {
localStorage.setItem('sec', this.time);// If still some time's left out then it'll continuously keep updated with browser localStorage
}
}
setTimeout(() => this._timerTick(), 1000);// For every 1sec timer gets updated here
}
Код CSS для таймера Blink, указанный ниже.
.blink_me {
animation: blinker 1s linear infinite;
}
@keyframes blinker {
50% {
opacity: 0;
}
}
.white {
color: white;
}
.red {
color: #ff0000;
}
- 1. Пользовательский счетчик таймера
- 2. Счетчик таймера при викторине
- 3. Как увеличить счетчик таймера (CountDownTimer)
- 4. Счетчик кликов с помощью таймера в JavaFX
- 5. Функция таймера в перегибе
- 6. Как создать счетчик таймера в JSF
- 7. C# Счетчик таймера в формате xx.xx.xx
- 8. Как создать счетчик таймера в C#
- 9. Установить значение фильтра в угловомJS
- 10. Activiti: необходимо получить счетчик триггера таймера
- 11. Функция таймера меняется
- 12. Функция таймера петли в avr?
- 13. Функция изменения таймера PCL
- 14. Простой JavaScript Функция таймера
- 15. питон 3.4, счетчик таймера вниз не работает
- 16. PHP счетчик функция
- 17. Функция циклирования таймера
- 18. Npapi set функция таймера
- 19. Функция работы таймера
- 20. 2 таймера arduino [2x millis()]
- 21. ГДЕ условие на угловомJS forEach
- 22. Функция таймера, вызывающая 2 раза javascript и enyo
- 23. Функция таймера таймера диспетчера, не вызываемая в просечной нити
- 24. Состояние не работает в угловомJS-контроллере
- 25. Динамически добавить переключатель в ионном угловомJS
- 26. Как использовать, если еще условие в угловомJs
- 27. Функция таймера не работает. Java
- 28. Сенсорный счетчик и функция выполнения
- 29. 2 Счетчик производительности AverageTimer32
- 30. Кнопка android запускает 2 таймера
создать с помощью JS и будет работать в определенно angular2 – anshuVersatile
Где Вы застряли? –
помогите мне найти путь для таймера секундомера в угловом2. –