Track the duration of continuous mouse movements on a webpage. A measurement begins when the cursor starts to move and ends when the cursor has stopped moving on the page. Reporting on duration happens thereafter. THis is what I have and works for while the mouse is moving and while it is stopped. However, I am confused how to track the start time and end time(i.e. the duration period of the mouse moving).
var myDiv = document.getElementById("myDiv");
var timeout;
//var startTime;
document.addEventListener("mousemove", function() {
myDiv.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
myDiv.innerHTML = "Stopped";
//console.log(Math.abs((startTime.getTime() - endTime.getTime())/1000));
}
You can count time on a different timer thread. Once you stop rest the timer.
var myDiv = document.getElementById("myDiv");
var timeout;
var timer = {stopped: true, time: 0};
setInterval(() => {
if (!timer.stopped) {
timer.time++;
}
}, 1000);
document.addEventListener("mousemove", function() {
timer.stopped = false;
myDiv.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
var totalTime = timer.time;
timer = {stopped: true, time: 0};
myDiv.innerHTML = 'Stopped! Total time: ' + totalTime + ' seconds';
}
<div id="myDiv"></div>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加