在网页上保持毫秒运动的计数

时间:2017-08-21 16:21:44

标签: javascript jquery

我想在我的页面上跟踪用户的IDLE时间(无鼠标或键盘移动)。我想要一个正在运行的计数器,因为当用户通过ajax提交时,该调用将从在页面上花费的时间中减去该时间。

time on page =  (Date.now() - startTime) - idleTime.

应该很容易我会想到在自定义javascript的函数()中粘贴一些内容但不知道如何计算。

1 个答案:

答案 0 :(得分:1)

我想你可以这样做。您可以从$column-width: (first: 210px, second: 200px, third: 100px) 方法获取总时间,如果您想跟踪更多事件,可以通过getIdleTime const

执行此操作

actionsToTrack
function TimeKeeper(selector) {
  const timeKeeper = document.querySelector(selector);
  const actionsToTrack = ['mousemove', 'mouseenter', 'mouseleave', 'keyup', 'keydown', 'keypress'];

  let lastMoveTime = new Date();
  let idleTime = 0;
  
  // this updates the time and updates the element showing the inactive time
  let update = (newTime) => {
    idleTime += newTime;
    timeKeeper.innerHTML = `${idleTime} ms`;
  };

  // will execute for every different kind of action
  // you could potentially log the action to see if it got caught or not
  const trackAction = (action) => function() {
    lastMoveTime = new Date();
  };

  setInterval(() => {
    let moveTime = new Date();
    let diff = moveTime - lastMoveTime;
    // i don't see 100 ms of inactivity necessarily as idle, but okay
    if (diff >= 100) {
      update(diff);
      lastMoveTime = moveTime;
    }
  }, 100);

  // attaches the handlers
  Object.keys( actionsToTrack ).forEach(action => 
    document.body.addEventListener(actionsToTrack[action], trackAction( actionsToTrack[action] ) )
  );

  // returns the idle time
  this.getIdleTime = () => {
    return idleTime;
  };

  // resets the idle time
  this.reset = () => {
    idleTime = 0;
  };
}

var tk = new TimeKeeper('#idleTime');
html,
body {
  position: absolute;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.timekeeper {
  position: absolute;
  top: 0;
  right: 0;
}

请注意,对于鼠标移动,光标必须传递身体本身,因为我没有任何内容我只是拉伸它...