gpt4 book ai didi

javascript - 以毫秒为单位记录网页上没有移动的情况

转载 作者:行者123 更新时间:2023-12-03 03:37:13 24 4
gpt4 key购买 nike

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

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

应该很容易,我想在自定义 JavaScript 的 function() 中添加一些内容,但不知道如何进行计数。

最佳答案

我想你可以这样做。您可以从 getIdleTime 方法获取总时间,如果您想跟踪更多事件,可以通过 actionsToTrack const

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;
}
<div id="idleTime" class="timekeeper"></div>

请注意,对于鼠标移动,光标必须通过主体本身,因为我没有任何内容,我只是拉伸(stretch)了它......

关于javascript - 以毫秒为单位记录网页上没有移动的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com