gpt4 book ai didi

javascript - 如何重启间隔?

转载 作者:行者123 更新时间:2023-11-29 20:46:34 25 4
gpt4 key购买 nike

我需要重新开始一个间隔,即当用户点击按钮时开始一个新的 1 秒间隔。

主页.html

<ion-header>
<ion-navbar>
<ion-title>
TimerDemo
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>

<h1>{{ time_elapsed }}</h1>
<button ion-button (click)="restart()">restart</button>

</ion-content>

首页.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

timestamp = new Date().getTime();
timer: any;
time_elapsed: string;


constructor(public navCtrl: NavController) {}

ionViewDidLoad() {
this.timer = setInterval(this.function, 1000);
}

function = () => {
let now = new Date().getTime();
let difference = now - this.timestamp;

let days = Math.floor(difference / (1000 * 60 * 60 * 24));
let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 24));
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);

this.time_elapsed = `${days} d ${hours} h ${minutes} m ${seconds} s`;
}

restart() {
clearInterval(this.timer);
this.timer = setInterval(this.function, 1000);
}

}

我希望能够在用户单击按钮并触发 restart() 方法时重新启动计时器 time_elapsed。实际结果是定时器没有重启。

最佳答案

试试这个

ionViewDidLoad() {
this.timer = setInterval(() => this.setTimeElapsed(), 1000);
}

setTimeElapsed() {
let now = new Date().getTime();
let difference = now - this.timestamp;

let days = Math.floor(difference / (1000 * 60 * 60 * 24));
let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 24));
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);

this.time_elapsed = `${days} d ${hours} h ${minutes} m ${seconds} s`;
}

restart() {
clearInterval(this.timer);
this.timer = setInterval(() => this.setTimeElapsed(), 1000);
}

关于javascript - 如何重启间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54307683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com