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

China☆狼群 提交于 2019-12-29 07:43:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/219322/how-can-i-use-javascript-timing-to-control-on-mouse-stop-and-on-mouse-move-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!