Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use javascript timing to control on mouse stop and on mouse move events

So I have a control (a map) on an aspx page. I want to write some javascript to onload setup the following:

  1. when mouse stops on control = some code

  2. when mouse moves = some code (but only if the move is longer than 250 mil sec)

This works to trigger code on stop and then on move...

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 cannot figure out how to introduce a delay into the on move code. I thought I had it 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 it does not behave as I thought it would. The on move "thread2" is never cleared by the stop. What am I missing?

like image 498
mrjrdnthms Avatar asked Oct 20 '08 18:10

mrjrdnthms


1 Answers

That is a tricky one. A little bit of tinkering resulted in this:

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 does not work is that mousemove fires repeatedly while the mouse is moving and you are starting new timeouts every time.

like image 165
Borgar Avatar answered Sep 19 '22 22:09

Borgar