如何获取应用无操作时长并实现无操作15秒触发提示功能
Got it, let's break down how to implement this feature—tracking user inactivity and showing a prompt when they haven't interacted for 15 seconds. Here's a straightforward, reliable approach:
Core Idea
We'll listen for all common user interactions (clicks, mouse moves, key presses, touches) and reset a timer every time the user acts. If the timer ever reaches 15 seconds without being reset, we'll trigger our alert.
Step 1: Set Up Timer Variables
First, we need to store our timer ID and define the inactivity threshold (15 seconds converted to milliseconds):
let inactivityTimer; const INACTIVITY_THRESHOLD = 15000; // 15 seconds in ms
Step 2: Create a Timer Reset Function
This function will clear any running timer and start a new one. When the threshold is hit, it fires our prompt:
function resetInactivityTimer() { // Clear existing timer to avoid multiple triggers clearTimeout(inactivityTimer); // Start new timer inactivityTimer = setTimeout(() => { // Your prompt here—we'll use the example alert alert('tap'); // You can replace this with a custom modal or notification too! }, INACTIVITY_THRESHOLD); }
Step 3: Listen for User Interactions
Attach event listeners to the document to catch all user actions. Every time the user interacts, we reset the timer:
// Reset timer on any of these events document.addEventListener('click', resetInactivityTimer); document.addEventListener('mousemove', resetInactivityTimer); document.addEventListener('keydown', resetInactivityTimer); document.addEventListener('touchstart', resetInactivityTimer); // For mobile devices
Step 4: Initialize the Timer
Don't forget to start the timer when your app or page loads:
// Start tracking inactivity as soon as the app loads resetInactivityTimer();
Quick Notes for Edge Cases
- Single-Page Apps: If you're using frameworks like React or Vue, make sure to remove event listeners when components unmount to prevent memory leaks.
- Custom Prompts: Replace the basic
alert('tap')with a styled UI component for a better user experience. - Adjust Timing: Tweak
INACTIVITY_THRESHOLDto change how long before the prompt appears (e.g.,30000for 30 seconds).
Full Working Example
Here's all the code put together:
let inactivityTimer; const INACTIVITY_THRESHOLD = 15000; // 15 seconds function resetInactivityTimer() { clearTimeout(inactivityTimer); inactivityTimer = setTimeout(() => { alert('tap'); }, INACTIVITY_THRESHOLD); } // Attach interaction listeners document.addEventListener('click', resetInactivityTimer); document.addEventListener('mousemove', resetInactivityTimer); document.addEventListener('keydown', resetInactivityTimer); document.addEventListener('touchstart', resetInactivityTimer); // Start the timer on app load resetInactivityTimer();
内容的提问来源于stack exchange,提问作者Italo Rodrigo

