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

后端 未结 1 1536
再見小時候
再見小時候 2020-12-19 08:12

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

相关标签:
1条回答
  • 2020-12-19 08:54

    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.

    0 讨论(0)
提交回复
热议问题