Reputation: 74
I want to capture the mouse pointer position after every 500 milliseconds for 10 secs lets suppose. Can someone please help?!
I tried using 'mousemove' event but couldn't move any further with this approach. Here's the code, hope this helps you. The removeEventListner on mousemove is not working correctly.
var loadTime;
var loadDate;
var clickTime;
var mousePositions = [];
var closeCapture = false;
var isTimerON = false;
var timer_div = document.getElementById('timer-section');
var x , y;
function mouseUpdate(e) {
if (isTimerON) {
x = e.pageX;
y = e.pageY;
// if the timer is ON and position capturing is OPEN then push
// the last pointer position to the array
if (!closeCapture){
var mouseUpdate = setInterval(function () {
mousePositions.push({
pos_x : x,
pos_y : y
});
}, 500);
}
}
else{
document.removeEventListener('mousemove', mouseUpdate);
}
}
function setTimer (time) {
var x = time;
document.addEventListener('mousemove', mouseUpdate);
if (isTimerON) {
var timer = setInterval(function() {
if (x >= 0){
timer_div.innerHTML = x;
console.log(x);
x--;
}
else {
//console.log(mousePositions);
isTimerON = false;
closeCapture = true;
clearInterval(timer);
console.log("timer off capture closed");
}
},1000);
}
}
function makeTime(x) {
return x.getHours() + " : " + x.getMinutes() + " : " + x.getSeconds();
}
function tii() {
isTimerON = true;
setTimer(10);
document.removeEventListener('click', tii);
}
document.addEventListener('DOMContentLoaded', function () {
loadCDate = new Date();
loadTime = makeTime(loadCDate);
console.log(loadTime);
document.addEventListener('click', tii);
});
<div id="timer-section"></div>
Upvotes: 0
Views: 652
Reputation: 5050
I would suggest capturing mousemove
events for the duration of your time limit (in this example I've set limit
to 10 seconds). The throttle
variable ensures you only capture once per that many milliseconds (in this example 500ms).
You can use the x/y co-ordinates of the mousemove event to get the current position of the mouse.
const limit = 10000
const throttle = 500
const start = (new Date).getTime()
let last = (new Date).getTime()
const handleMouseMove = (event) => {
const now = (new Date).getTime()
if ((now - start) > limit) {
document.removeEventListener('mousemove', handleMouseMove)
return
}
if ((now - last) < throttle) {
return
}
last = now
// do whatever you want to do within your time limit here
}
document.addEventListener('mousemove', handleMouseMove)
Upvotes: 4
Reputation: 346
I think you need this http://devdocs.io/lodash~4/index#throttle. the throttle function will make you capture event in a setup freq. If you code is handle every callback of mouse event. you program will be freeze.
Upvotes: 1