アプリケーションでユーザーのアイドルタイムアウトを検出する必要があります。私のアプリケーションはネイティブJavaScriptとAngularの両方を使用しています。以下に実装したHTML + JavaScriptページで:
<script>
var inactivityTime = function () {
var time;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
document.onclick = resetTimer;
document.onwheel = resetTimer;
function callApi() {
alert("Idle for 3 seconds. You can call your api here");
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(callApi, 3000);
// 5 minute = 60000 * 5;
// 1000 milliseconds = 1 second
}
};
window.onload = function() {
inactivityTime();
}
</script>
期待どおりに機能しています。
私がAngularプロジェクトで使用しているのと同じですが、Angularコードも機能していますが、1つの小さな問題が観察されました。最初に私のAngularコードを参照してください。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'project';
time;
ngOnInit() {
this.inactivityTime();
this.resetTimer();
}
inactivityTime() {
document.onmousemove = this.resetTimer;
document.onkeypress = this.resetTimer;
document.onclick = this.resetTimer;
document.onwheel = this.resetTimer;
}
resetTimer() {
clearTimeout(this.time);
this.time = setTimeout(() => {
alert('Idle for 3 seconds. You can call your api here');
}, 3000);
}
}
私が直面している問題は、マウスの移動/キーを押してもページの読み込み時にアラートが呼び出されることです。その後、すべてが期待どおりに機能しています。しかし、ページの読み込み時には機能しません。
ここでヘルプをリクエストします。
ありがとうございました!
最善のアプローチは、Angular HostListenerデコレータを使用して、それをドキュメントにバインドすることです。
export class AppComponent {
time: number;
ngOnInit() {
this.resetTimer();
}
@HostListener('document:mousemove')
@HostListener('document:keypress')
@HostListener('document:click')
@HostListener('document:wheel')
resetTimer() {
clearTimeout(this.time);
this.time = setTimeout(() => {
alert('Idle for 3 seconds. You can call your api here');
}, 3000);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加