Javascript 实现定时器,刷新时处理?
我已经编写了一个组件来跟踪时间。我目前正在使用Javascript 实现定时器,刷新时处理?,javascript,angular,typescript,Javascript,Angular,Typescript,我已经编写了一个组件来跟踪时间。我目前正在使用Localstorage保存currentTime,以防用户点击刷新。但是,我发现这个解决方案不是一个很好的解决方案,因为用户可以编辑localstorage。另一方面,我可以使用数据库来存储这些信息,但它会降低我不想要的页面速度 除了使用LocalStorage存储我的时间之外,还有其他解决方案吗?我不希望用户编辑localstorage export class MainComponent implements OnInit { pri
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" );
}
}
}
一种可能的替代方法是节省用户在服务器端的会话中访问页面的时间。会话存储在服务器内存中,并与登录绑定,可以在服务器上保存信息,从而使其安全。一旦用户注销,信息就会被丢弃,因此它比数据库更高效 有一个PHP示例,说明如何在会话中存储内容。有趣的是,它们显示了如何在页面之间记住会话,因此您将始终能够访问currentTime
询问除使用数据库存储外是否还有其他解决方案。为了提高效率。从数据库的可能性来看,我假设您必须登录才能使用此服务。currentTime是否需要在不同的登录之间保留,或者在您注销后是否可以丢弃?@Emenpy将其保留在服务中,或者学习如何使用类似redux的存储。。。我不明白为什么一个简单的服务不能:p@FRECIA即使在服务中,刷新也会启动计时器。@NocNit我使用计时器来测量用户在某个页面上停留的时间。一旦注销/重新登录,计时器将重置。但是,我不希望在用户刷新页面时重置它。通过在localStorage中存储,我可以从localStorage中检索重置后的时间。