Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - How to detect when mouse has stopped

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:

  1. Even though I am calling 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?
  2. I would like to break 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's really simple: when the mouse is moved, set a timeout for XXX milliseconds in the future. Also, clear any past timeouts to reset the time. Like this in the mousemove listener

clearTimeout(timer);
timer=setTimeout(mouseStopped,300);

See this JSFiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...