How to use javascript to control mouse stop and mouse move events

So, I have a control (map) on an aspx page. I want to write javascript to configure onload as follows:

  • when the mouse stops during control = some code

  • when the mouse moves = some code (but only if the movement is longer than 250 mil)

This works to run the code when stopped, and then when moving ...

function setupmousemovement() { var map1 = document.getElementById('Map_Panel'); var map = document.getElementById('Map1'); map1.onmousemove = (function() { var onmousestop = function() { //code to do on stop }, thread; return function() { //code to do on mouse move clearTimeout(thread); thread = setTimeout(onmousestop, 25); }; })(); }; 

But I canโ€™t figure out how to introduce a delay in the transition code. I thought I had this with this ...

 function setupmousemovement() { var map1 = document.getElementById('Map_Panel'); var map = document.getElementById('Map1'); map1.onmousemove = (function() { var onmousestop = function() { //code to do on stop clearTimeout(thread2); }, thread; return function() { thread2 = setTimeout("code to do on mouse move", 250); clearTimeout(thread); thread = setTimeout(onmousestop, 25); }; })(); }; 

But he does not behave as I thought. The still image "thread2" is never cleared. What am I missing?

+6
javascript timeout onmousemove
source share
1 answer

It's complicated. The result is a bit:

 function setupmousemovement() { var map1 = document.getElementById('Map_Panel'); map1.onmousemove = (function() { var timer, timer250, onmousestop = function() { // code to do on stop clearTimeout( timer250 ); // I'm assuming we don't want this to happen if mouse stopped timer = null; // this needs to be falsy next mousemove start }; return function() { if (!timer) { // code to do on start timer250 = setTimeout(function () { // you can replace this with whatever // code to do when 250 millis have passed }, 250 ); } // we are still moving, or this is our first time here... clearTimeout( timer ); // remove active end timer timer = setTimeout( onmousestop, 25 ); // delay the stopping action another 25 millis }; })(); }; 

The reason your code doesn't work is because mousemove fires repeatedly while the mouse moves, and you start new timeouts every time.

+6
source share

All Articles