获取 keyDown 和 keyUp 之间的时间间隔然后存储在对象中

Get timeInterval between keyDown & keyUp then store in object

我想获取按下每个键的 keydown 和 keyup 事件之间的时间间隔

var down = Rx.Observable.fromEvent(document, "keydown")
    .filter(e => !e.repeat)

var up = Rx.Observable.fromEvent(document, "keyup");

var actions = {}
var keyPress = down.merge(up)
           .groupBy(e => e.keyCode)
        //Ideally, get timeInterval here
           .mergeAll()
           .do(actions[e.key].push(e.timeInterval))

我想像这样构造动作对象

actions = {
           'w': {0: 1000ms, 1: 1123ms},
           'd': {0: 402ms}
          } 

哈尔普好吗?

开始时间变量,然后是差异变量和格式。冲洗并重复,您可以将其放入您自己的自定义函数中 运行 on keydown/keyup 或其他任何内容,然后只需创建数据并将其格式化为您想要的对象即可。

var startTime = Date.now();
var elapsedTime = ((Date.now() - startTime) / 1000);

试试这个:

const keyDown$ = Rx.Observable.fromEvent(document, "keydown")
  .filter(e => !e.repeat)

const keyUp$ = Rx.Observable.fromEvent(document, "keyup");

keyDown$
  .mergeMap(keyDown => // For every key down we start a new observable, waiting for the-same-key up event
    keyUp$.filter(keyUp => keyUp.keyCode === keyDown.keyCode)
    .take(1)
    .map(keyUp => ({
      keyCode: keyUp.keyCode,
      key: keyUp.key,
      duration: keyUp.timeStamp - keyDown.timeStamp
    }))
  )
  .scan((actions, action) => { // The scan collects all the actions aggregated in a map by key. It emits the current aggregated map for every action
    actions[action.key] = actions[action.key] || {};
    const actionIndex = Object.keys(actions[action.key]).length;
    actions[action.key][actionIndex] = `${Math.round(action.duration)}ms`;
    return actions;
  }, {})
  .subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>