请求实现:获取按键keydown与keyup的timeInterval并存储至指定对象
Track Keydown-Keyup Time Intervals and Store in Structured
actions Object Got it, let's break down how to implement this. The core idea is to track when each key is pressed, calculate the time difference when it's released, and store all that data in a structured actions object. Here's a practical, tested solution:
Step 1: Initialize Storage Variables
First, we need a temporary store for keydown timestamps and our final actions object to hold the event data:
// Temporary map to hold timestamps when each key is pressed const keyDownTimestamps = {}; // Structured object to store all key event data (customize this structure as needed) const actions = { keyEventHistory: [] // Each entry represents a full press-release cycle };
Step 2: Add Event Listeners
We'll listen for keydown to record the start time, and keyup to calculate the interval and save the data:
// Listen for keydown events document.addEventListener('keydown', (event) => { // Only record the first keydown if the key is held down (prevents duplicate entries) if (!keyDownTimestamps[event.key]) { keyDownTimestamps[event.key] = Date.now(); } }); // Listen for keyup events document.addEventListener('keyup', (event) => { const key = event.key; const pressTimestamp = keyDownTimestamps[key]; // Only proceed if we have a matching keydown timestamp if (pressTimestamp) { const releaseTimestamp = Date.now(); const timeInterval = releaseTimestamp - pressTimestamp; // Interval in milliseconds // Push the data into our actions object (adjust the structure to fit your needs) actions.keyEventHistory.push({ key: key, keyCode: event.keyCode, // Optional: include if you need legacy key codes pressTimestamp: pressTimestamp, releaseTimestamp: releaseTimestamp, timeInterval: timeInterval }); // Clean up the temporary timestamp to avoid stale data delete keyDownTimestamps[key]; } });
Step 3: Customize the actions Structure
If you prefer grouping events by key instead of a flat history, you can adjust the actions object like this:
const actions = { eventsByKey: {} // Keys are key names, values are arrays of press-release cycles };
Then update the keyup handler to push into the grouped structure:
if (!actions.eventsByKey[key]) { actions.eventsByKey[key] = []; } actions.eventsByKey[key].push({ pressTimestamp: pressTimestamp, releaseTimestamp: releaseTimestamp, timeInterval: timeInterval });
Key Notes & Edge Cases
- Prevent Duplicate Entries: The check for
!keyDownTimestamps[event.key]ensures we don't record multiple timestamps when a key is held down (sincekeydownfires repeatedly for held keys). - Special Keys: Modifier keys like
Shift,Control, andAltwork the same way—theirevent.keyvalues are just their names, so they'll be tracked correctly. - Memory Management: If your app runs for long periods, consider adding logic to trim old entries from
actionsto avoid excessive memory usage. - Browser Compatibility:
event.keyis supported in all modern browsers. For legacy support, you can mapevent.keyCodeto key names using a lookup table, but this is rarely needed now.
内容的提问来源于stack exchange,提问作者Spankied
相关产品推荐
相关产品推荐

