Rob Rob - 4 months ago 9
Javascript Question

RxJS count how long hovered over button

I am able to log to the console every time someone hovers over a button, but how would I could how many seconds this had happened for and aggregate the total?

var result = document.getElementById('result');
var source = Rx.Observable.fromEvent(result, 'mouseover');
var subscription = source.subscribe(
function (x) {
console.log('Hovered!');
}
);

Answer

If I am understanding your requirements correctly, You would need to check when the mouse also leaves the element as well, and then use and operator like scan to sum the total. A relatively simple way to do this would be get a timestamp of the mouseover and then sample on the mouseout event:

var result = document.getElementById('result');
var mouseOver = Rx.Observable.fromEvent(result, 'mouseover');
var mouseOut  = Rx.Observable.fromEvent(result, 'mouseout');

mouseOver
  //Get the time of the mouseover event
  .timestamp()
  //Don't emit until the mouseOut triggers
  .sample(mouseOut)
  //Extract only the timestamp value
  .pluck('timestamp')
  //Get a new timestamp (remember this is *after* mouse out)
  .timestamp()
  //Compute the timeinterval
  .map(x => x.timestamp - x.value)
//Add the new time interval to the running total
.scan((total, diff) => total += diff, 0)
.subscribe(x => console.log(x));
Comments