javascript - How to detect when mouse has stopped -


i have written following javascript code. using detect when mouse moving , when has stopped. mousestopped() function loop of hundreds of items tell me mouse has stopped, want call when 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 have following problems:

  1. even though calling clearinterval(checkmovement), doesn't stop iterating; running continuously, cause problem of calling mousestopped() multiple times. why not stopping?
  2. i break mousestopped() in middle of operation if mouse moved before completed loop. why setting stoploop = true; however, doesn't seem working intended. how can achieve these?

thanks.

edits

it's simple: when mouse moved, set timeout xxx milliseconds in future. also, clear past timeouts reset time. in mousemove listener

cleartimeout(timer); timer=settimeout(mousestopped,300); 

see jsfiddle.


Comments