You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求实现:获取按键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 (since keydown fires repeatedly for held keys).
  • Special Keys: Modifier keys like Shift, Control, and Alt work the same way—their event.key values 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 actions to avoid excessive memory usage.
  • Browser Compatibility: event.key is supported in all modern browsers. For legacy support, you can map event.keyCode to key names using a lookup table, but this is rarely needed now.

内容的提问来源于stack exchange,提问作者Spankied

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:48:53