Reputation: 1100
I have written the following JavaScript code. I am using it to detect when the mouse is moving and when it has stopped. MouseStopped() function is a loop of hundreds of items that will tell me where the mouse has stopped, so I want to call it only when the mouse has stopped.
var CheckMovement;
var stopLoop = false;
var n = 0;
canvas.addEventListener('mousemove', function (evt) {
CheckMovement = setInterval(function () { HasMouseStopped(evt) }, 250);
}, false)
function HasMouseStopped(evt) {
var mousePos = getMousePos(canvas, evt);
newMouseX = mousePos.x;
newMouseY = mousePos.y;
if ((newMouseX !== mouseX) && (newMouseY !== mouseY)) {
stopLoop = true;
} else {
//stopped moving
clearInterval(CheckMovement);
stopLoop = false;
n = 0;
MouseStopped();
}
mouseX = newMouseX;
mouseY = mousePos.y;
}
function MouseStopped() {
while (arr.length > n) {
if (stopLoop) { break; }
if (ctx.isPointInPath(mouseX, mouseY)) {
//tooltip text
ctx.font = '12pt Candara';
ctx.fillStyle = 'black';
ctx.fillText(arr[n], mouseX + 10, mouseY - 5);
break;
}
n++;
}
}
Now I have the following problems:
clearInterval(CheckMovement)
, it doesn't
stop iterating; it is running continuously, which cause the problem of
calling MouseStopped()
multiple times. Why is it not stopping?MouseStopped()
in the middle of its operation if the mouse is moved before it completed its the loop. This is why I am setting stopLoop = true;
However, that also doesn't seem to be working as intended. How can I achieve these?Thanks.
EDITS
Upvotes: 18
Views: 18454
Reputation: 7894
This can be done very simply: when the mouse is moved, set a timeout for n
milliseconds in the future. Also, clear the last timeout to reset the time. Like the following listener.
let timer
canvas.addEventListener(`mousemove`, () => {
clearTimeout(timer)
timer = setTimeout(mouse_stopped, 300)
})
See this JSFiddle.
Upvotes: 32
Reputation: 2127
After a little thinking, I think the debounce
function may meet your needs. Lodash.js provides it.
Upvotes: -1