<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
http-equiv
=
"X-UA-Compatible"
content
=
"IE=edge"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
title
>
JavaScript for Capturing Mouse Positions
After Every Given Interval
</
title
>
</
head
>
<
body
>
<
div
id
=
"timer-section"
style
=
"text-align: center;"
>
Timer will appear here!
</
div
>
<
div
id
=
"output-section"
></
div
>
<
script
type
=
"text/javascript"
>
// Timer
let limit = 10000;
// Time interval of 500 millisecond set
let throttle = 500;
// Timer is off initially
let timerON = false;
let start;
let last;
let mousePositions = [];
// Records the time when the timer starts
function makeTime(s) {
return s.getHours() + " : " + s.getMinutes()
+ " : " + s.getSeconds();
}
// When the first click to start the timer,
// this function will get envoked
function clickEnvoke() {
start = (new Date).getTime();
mousePositions.push({
time: {
start: makeTime(new Date())
}
});
console.log(mousePositions);
last = (new Date).getTime();
let time = 10;
// Timer has started
timerON = true;
document.removeEventListener('click', clickEnvoke);
document.addEventListener('mousemove', mouseUpdate);
let timer = setInterval(function () {
if (time >= 0)
document.getElementById('timer-section')
.innerHTML = time;
else {
// Mouse positions will be stop recording
// as timer is 0
timerON = false;
clearInterval(timer);
document.removeEventListener('mousemove', mouseUpdate);
// JSON data need to converted into
// string to print as object
document.getElementById('timer-section').innerHTML = "";
document.getElementById('timer-section').innerHTML +=
JSON.stringify(mousePositions);
}
time--;
}, 1000);
}
// Capturing mouse positions envoked
function mouseUpdate(event) {
let now = (new Date).getTime();
if (timerON) {
if (now - start > limit) {
return document.removeEventListener(
'mousemove', mouseUpdate);
}
if (now - last <
throttle
) {
return;
}
last
=
now
;
mousePositions.push({
info: {
x: event.pageX,
y: event.pageY
}
});
}
else
console.log(mousePositions);
// Do whatever you want to do within your
// time limit here
}
// Initial HTML page is empty and DOM is loaded
// upon first click our functions will work
document.addEventListener('DOMContentLoaded', function () {
let loadTime = (new Date).getTime();
document.addEventListener('click', clickEnvoke);
});
</script>
</
body
>
</
html
>