我需要一个计时器来暂时禁用鼠标悬停事件

时间:2016-09-14 01:18:17

标签: javascript javascript-events

我正在寻找一种暂时禁用鼠标悬停事件的简单方法,实际上是1000毫秒。我所有这样做的尝试都失败了。当鼠标悬停在div的边缘时鼠标进入几次,我试图阻止我的图像闪烁。这是我的代码,非常感谢您的帮助。

var ranNum, result_10, resultFloor, piccy, audio;

function myFunction() {
	ranNum = Math.random();
	result_10 = (ranNum * 5) + 1;
	resultFloor = Math.floor(result_10);
	piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
	document.getElementById("demo").innerHTML = piccy;
	audio = document.getElementById("audio");
       audio.play();
}
<div id="container">
	<div id="demo" onmouseenter="myFunction()">This</div>
    <audio id="audio" src="pop.wav" ></audio>
</div>

3 个答案:

答案 0 :(得分:1)

这是一种快速而肮脏的方法。只需使用引用函数的变量,并将引用更改为指向不执行任何操作的函数,然后返回到原始函数。

我同意Kosch关于使用下划线/ lodash去抖功能的建议,如果你已经在使用这些库,或者如果你看到他们帮助你的不仅仅是这一个案例。

var ranNum, result_10, resultFloor, piccy, audio;

function myFunction() {
        disableMouseOverHandler();
 	ranNum = Math.random();
	result_10 = (ranNum * 5) + 1;
	resultFloor = Math.floor(result_10);
	piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
	document.getElementById("demo").innerHTML = piccy;
	audio = document.getElementById("audio");
       audio.play();

}

function doNothing() {
}

var mouseOverHandler = myFunction;

function disableMouseOverHandler() {
  mouseOverHandler = doNothing;
  setTimeout(function(){ mouseOverHandler = myFunction; }, 3000);
  //I used 3000ms (3 seconds) to make it more pronounced.
}
<div id="container">
	<div id="demo" onmouseenter="mouseOverHandler()">This</div>
    <audio id="audio" src="pop.wav" ></audio>
</div>

答案 1 :(得分:1)

var myFunctionDisabled = null;

function disableMyFunction() {
  clearTimeout(myFunctionDisabled);
  myFunctionDisabled = setTimeout(function() { myFunctionDisabled = false; }, 1000);
}

function myFunction() {
  if (myFunctionDisabled) return;
  ...
}

答案 2 :(得分:1)

这将停止闪烁:

var ranNum, result_10, resultFloor, piccy, audio;
var isPlaying = false;

var audio = document.getElementById("audio");
function myFunction() {
  if (!isPlaying) {
	isPlaying = true;
	ranNum = Math.random();
	result_10 = (ranNum * 5) + 1;
	resultFloor = Math.floor(result_10);
	piccy = "<img src=\"http://d2.alternativeto.net/dist/icons/cloudapp_2094.png?width=64&height=64&mode=crop&upscale=false\" />";
	document.getElementById("demo").innerHTML = piccy;
    // check every 1/2 second to see if the audio has ended
	var t = setInterval(function() {
     console.log(audio.ended);
	   if (audio.ended) {
	      isPlaying = false;
	      clearInterval(t);
	   }
	}, 500);
	audio.play();
  }
}
<div id="container">
	<div id="demo" onmouseenter="myFunction()">This</div>
    <audio id="audio" src="http://freewavesamples.com/files/Casio-MT-45-Pops.wav" ></audio>
</div>