Rob Rob - 1 year ago 46
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) {

Answer Source

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');

  //Get the time of the mouseover event
  //Don't emit until the mouseOut triggers
  //Extract only the timestamp value
  //Get a new timestamp (remember this is *after* mouse out)
  //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));