获取keyDown&之间的timeInterval keyUp然后存储在对象中

时间:2018-02-22 20:24:50

标签: javascript rxjs keyevent

我希望在按下每个键的keydown和keyup事件之间得到timeInterval

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}
          } 

Haalp拜托?

2 个答案:

答案 0 :(得分:0)

开始时间的变量,差异的变量和格式。冲洗并重复,您可以将它放在自己的自定义函数中以在keydown / keyup或其他任何东西上运行,然后只需按照您的需要创建数据并将其格式化为对象。

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

答案 1 :(得分:0)

试试这个:



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>
&#13;
&#13;
&#13;