【问题标题】:Cleared countdown timer when you restart the page重新启动页面时清除倒数计时器
【发布时间】:2016-12-08 20:13:44
【问题描述】:

我在打字稿上做了一个倒计时
现在我们需要使定时器在重启后不会重置,存储在 localStorage 中。
像所有逻辑上的真实一样,但仍然抛出

代码如下:

PasteBin link

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); 

【问题讨论】:

  • 您可以在此处包含问题的代码。另外,请包括代码抛出的错误类型。另外,您不应该存储结束时间,而不是当前时间吗?您始终可以获取当前时间。
  • 没有报错,只是重置了重启的时间,不应该的,而且代码不能附加,编辑报错
  • 我保存了当前时间
  • 我编辑了问题以包含代码。似乎工作正常。
  • 好的。仅通过阅读提供的代码很难判断出什么问题。查看调用代码的外观会很有用,即调用 CountdownService.start() 的代码。你是什​​么意思'重置时间'?重新启动是什么意思 - 关闭浏览器选项卡或重新启动操作系统?这是否在浏览器中运行?您可以使用调试工具查看是否设置了 localStorage 项吗?此外,您似乎没有使用lsTime。抱歉这些问题,但我不明白您为什么需要保存当前时间以倒计时到特定日期。您想要实现的场景是什么?

标签: typescript local-storage


【解决方案1】:

看起来调用代码设置了相对于当前时间的结束时间。每次刷新页面时,它都会重新计算一个新的结束时间,并且计数器似乎会重置。

您需要调整逻辑 - 我建议改为存储结束时间。这可以在您的 CountdownService 课程之外完成。

调整CountdownService.start() 方法以获取Date 对象(表示绝对时间点,而不是与当前时间的相对偏移)。

public start(deadline: Date, _callback:Function) {
    this.callback = _callback;
    this.initializeClock(deadline);
}

在您使用CountdownService 的代码中,如果尚未设置结束日期,请使用您的LS 服务保存结束日期。像这样的:

let storage = new LS();
let deadline = storage.get('deadline');

if (!deadline) { // set end time if not set already
    let timeData = this.test['time'].split(':'); 

    console.log(timeData); // ["1", "1"]
    // `+new Date` is a trick for converting a date to milliseconds
    deadline = new Date(+new Date() + (timeData[0] * 3600 + timeData[1] * 60) * 1000);
}


this.cds.start(deadline, this.endTestCallback); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多