OnmouseMove not work with SetTimeOut and Alerts in

2019-04-15 19:03发布

What's wrong with this code? It works in IE and FireFox, but Chrome does not work. The idea is that the function fnTimeOut will be triggered in 5 seconds after onmousemove (fnTimeOut was attach in onmousemove in document). It´s ok. But when, in Chrome, I click on the button "ok" to function fnAlert is triggered instantly. It should be shot just 5 seconds after I move the mouse ... help me please.


<input type="button" onclick="alert(1);" value="ok">


<script>

document.onmousemove = fnTimeOut;

var t = null;

function fnAlert()
{
    alert(2);
}

function fnTimeOut()
{
    clearTimeout( t );
    t = setTimeout( fnAlert, 5000 );
}
</script>

4条回答
等我变得足够好
2楼-- · 2019-04-15 19:27

onmousemove gets fired everytime your mouse moves over the document, so your the alert only shows after the mouse stops moving.

Saying that, it worked fine on my Chrome install, this is the following code.

<html>
<head>
  <script>

  document.onmousemove = fnTimeOut;

  var t = null;

  function fnAlert()
  {
      alert(2);
  }

  function fnTimeOut()
  {
      clearTimeout( t );
      t = setTimeout( fnAlert, 5000 );
  }
  </script>


</head>
<body></body>

</html>
查看更多
forever°为你锁心
3楼-- · 2019-04-15 19:43

I must be missing something. Your button has an onclick that says to show an alert box. There's no code there trying to delay that alert.

I can't figure out how on earth FF and IE would not display the alert immediately when clicking the button.

If what you want is for fnAlert to be called 5 seconds after a mousemove or a click of the button, you should set your onclick on the button to "fnTimeOut()"

查看更多
萌系小妹纸
4楼-- · 2019-04-15 19:45

As far as i read, the alert and confirm statements do reset the settimeout timers, which leads to an immediate execution of given code while flushing.

I didn't try myself, but maybe you could confirm this modifying the content of the click (currently an alert) by a null or random variable statement ?

查看更多
萌系小妹纸
5楼-- · 2019-04-15 19:51

The same issus, I think it's a bug of Chrome browser… In chrome 8 + Win XP; it's wrong; But Chrome 10 + WinXp is ok; and chrome 18 it's wrong again……but it's NOT reappear on some OS (such as Linux...). Someone say that This is not a browser bug, but an OS or maybe even hardware bug.

In my code, I use "onmouseover"/"onmouseout" to replace "onmousemove". It looks ok now.

BUT, in document element mouseOVER difficult...

查看更多
登录 后发表回答