【问题标题】:Implementing Timer, handling on Refresh?实现定时器,处理刷新?
【发布时间】:2018-11-03 00:30:03
【问题描述】:

我编写了一个可以跟踪时间的组件。我目前正在使用Localstorage 来保存currentTime,以防万一用户点击刷新。但是,我发现这个解决方案并不是一个很好的解决方案,因为用户可以编辑localstorage。另一方面,我可以使用数据库来存储这些信息,但它会减慢我不想要的页面速度。

除了使用LocalStorage 来存储我的时间之外,还有其他解决方案吗?我不希望用户编辑localstorage

export class MainComponent implements OnInit {

    private start: number = null;
    private uiTimerId: number = null;

    constructor() {
    }

    private updateUI(): void {

        let delta = performance.now() - this.start;
        this.someUIElement.textContent = delta.toFixed() + "ms";
    }

    ngOnInit() {

        this.start = parseFloat( window.localStorage.getItem( "timerStart" ) );
        if( !this.start ) {
            this.start = performance.now();
            window.localStorage.setItem( "timerStart", this.start );
        }

        this.uiTimerId = window.setInterval( this.updateUI.bind(this), 100 ); // 100ms UI updates, not 1000ms to reduce UI jitter
    }

    buttonClick = function() {
        if( this.uiTimerId != null ) {
            window.clearInterval( this.uiTimerId );
            window.localStorage.removeItem( "timerStart" );
        }
    }
}

【问题讨论】:

  • 询问除了使用数据库存储之外是否还有其他解决方案。出于效率目的。
  • 从数据库的可能性来看,我假设您必须登录才能使用此服务。 currentTime是否需要在不同的登录之间保留,还是可以在注销后丢弃?
  • @Emenpy 要么将其保存在服务中,要么学习如何使用像 store github.com/ngrx/store 这样的 redux ...我不明白为什么一个简单的服务不会这样做:p
  • @FRECIA 即使它在服务中,刷新也会重新启动计时器。
  • @NocNit 我正在使用计时器来测量用户在某个页面停留的时间。注销/重新登录后,计时器将重置。但是,我不希望它在用户刷新页面时重置。通过存储在 localStorage 中,如果它被重置,我可以从 localstorage 中检索时间。

标签: javascript angular typescript


【解决方案1】:

一种可能的替代方法是在服务器端的会话中节省用户访问页面的时间。会话存储在服务器内存中并与登录相关联,并且可以在服务器上保存信息,从而使其安全。一旦用户退出,信息就会被丢弃,因此它比数据库更有效。

This SO question 有一个关于如何在会话中存储内容的 PHP 示例。巧妙的是,它们显示了如何在页面之间记住会话,因此您将始终可以访问 currentTime。

Another good SO link

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多