Cuckoo Cuckoo - 2 months ago 7
Javascript Question

I need a timer to temporarily disable mouseover event

I'm looking for a simple way to temporarily disable a mouseover event, for literally 1000 miliseconds. All my attempts to do so, have so-far failed. I am trying to stop my images from flickering when the mouse enters several times as it hovers over the edge of the div. Here is my code, many thanks in advance for your help.



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>




Mic Mic
Answer

Here's a quick and dirty approach. Simply uses a variable referencing a function, and changes the reference to point to a function that does nothing, then back to the original function.

I agree with Kosch's suggestion of using the underscore/lodash debounce function if you're already using those libraries or if you see them helping you in more than just this one case.

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>