-2
タイマーが再起動後にリセットされないように、私はタイプレットの
にカウントダウンタイマーを作成しました。真のすべてのような
は、論理的に作られたが、それでもページを再起動すると、カウントダウンタイマーがクリアされました
コード以下スロー:
LSクラス
export class LS {
public set (key: string, data: any) {
let result = (data.constructor == Object) ? JSON.stringify(data) : data;
localStorage.setItem(key, result);
}
public get (key: string) : any {
let jsonObject = null;
let data = localStorage.getItem(key);
try {
jsonObject = JSON.parse(data);
}
catch(e) {
jsonObject = data;
}
return jsonObject;
}
public rm(key:string) {
localStorage.removeItem(key);
}
}
CountdownServiceクラス
export class CountdownService {
protected timeData: Object = {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
public ONE_SECONDS = 1000;
protected callback:Function;
protected ls:LS;
protected nameTimeData:string = 'timingData';
constructor() {
this.ls = new LS();
}
public start(hours: number, minutes:number, _callback:Function) {
this.callback = _callback;
let milliseconds = this.toMilliseconds(hours, minutes);
let deadline = new Date(Date.parse(new Date().toString()) + milliseconds);
this.initializeClock(deadline);
}
public getTimeData():Object {
return this.timeData
}
protected toMilliseconds(hours, minutes) {
let secondsHours = hours * 3600;
let secondsMinutes = minutes * 60;
return (secondsHours + secondsMinutes) * this.ONE_SECONDS;
}
protected getTimeRemaining(endTime) {
let currentTime = new Date().toString();
/*let lsTime;
// This block does not work correctly
if (this.ls.get(this.nameTimeData) != null) {
lsTime = this.ls.get(this.nameTimeData);
console.log(lsTime);
this.ls.set(this.nameTimeData, new Date().toString());
} else {
this.ls.set(this.nameTimeData, new Date().toString());
lsTime = this.ls.get(this.nameTimeData);
}
*/
let t = Date.parse(endTime) - Date.parse(currentTime);
let seconds = Math.floor((t/this.ONE_SECONDS) % 60);
let minutes = Math.floor((t/this.ONE_SECONDS/60) % 60);
let hours = Math.floor((t/(this.ONE_SECONDS * 60 * 60)) % 24);
let days = Math.floor(t/(this.ONE_SECONDS * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
protected initializeClock(endTime) {
let updateClock =() => {
let t = this.getTimeRemaining(endTime);
this.timeData['days'] = t['days'];
this.timeData['hours'] = ('0' + t.hours).slice(-2);
this.timeData['minutes'] = ('0' + t.minutes).slice(-2);
this.timeData['seconds'] = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeInterval);
this.callback();
}
};
updateClock();
var timeInterval = setInterval(updateClock, this.ONE_SECONDS);
}
}
呼び出し元のコードは、現在の時刻に終了時間を相対的に設定のように見えます
let timeData = this.test['time'].split(':');
console.log(timeData); // ["1", "1"]
this.cds.start(timeData[0], timeData[1], this.endTestCallback);
このコードを質問に含めることができます。また、コードがどんなタイプのエラーを投げるかも含めてください。また、現在の時刻ではなく、終了時刻を保存してはいけませんか?現在の時刻はいつでも取得できます。 –
エラーはありません。再起動時にリセットするだけです。コードを添付することはできません。編集者は –
を保存しています。 –