0

My index.html:

<!DOCTYPE html> 
<html> 
<head>
<meta charset="UTF-8">
</head>
<body>

<div id="test-1">
    <img id="test" src="thumb1.png" width="15%" onmouseover="over(this)" 
        onmouseout="out(this)">
</div>

<script>
    function over(x) {
        document.getElementById('test').setAttribute('src','thumb.webp');
        document.getElementById('test').setAttribute('width','15%');
        var Delay;
        Delay = setTimeout(thumb2, 4000);
    }

    function out(x) {
        document.getElementById('test').setAttribute('src','thumb1.png');
    }

    function thumb2(){
        document.getElementById('test').setAttribute('src','thumb2.png');
    }
</script>

</body> 
</html>

Hi, I already did some searches, but nothing satisfactory to fix the problem..

I would like some solution for this:

The onmouseover event is executed, and 1 second later, the onmouseout event is also called and setTime that was executed by the over function continues to count, reproducing a visual bug.

Is there any way to break the setTimer called by onmouseover event, when the onmouseout event is called?

2
  • so you want the timer to interrupt if the mouse is moved out of the element before the countdown is finished? Commented Nov 7, 2018 at 14:31
  • @messerbill Yes, that's it. Commented Nov 7, 2018 at 14:32

1 Answer 1

2

Use clearTimeout

<script>
    var Delay;
    function over(x) {
        document.getElementById('test').setAttribute('src','thumb.webp');
        document.getElementById('test').setAttribute('width','15%');
        Delay = setTimeout(thumb2, 4000);
    }

    function out(x) {
        clearTimeout(Delay);
        document.getElementById('test').setAttribute('src','thumb1.png');
    }

    function thumb2(){
        document.getElementById('test').setAttribute('src','thumb2.png');
    }
</script>

You can see a working example at w3wchools.com

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, glad to help. You could mark the answer as correct solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.