Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using clearTimeout to cancel a timeout event

I have the following code but the clear timeout doesn't work and I can't understand why, does anyone have any ideas? (Using the Prototype framework)

function foo() {
    $("navigation").observe('mouseover',
        function (event) {
            clearTimeout(bar);
        }
    ).observe('mouseout',
        function (event) {
            setTimeout(bar, 1000);
        }
    );
}

function bar() {
    alert("hi");
}
like image 218
Rich Avatar asked Dec 12 '09 14:12

Rich


People also ask

How do I cancel setTimeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

Can I use clearTimeout inside setTimeout?

clearTimeout() inside setTimeout() method not working in JSIt does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function.

Can we clear setTimeout?

This will be the ID that was returned by the setTimeout() function. You can clear the timeout by using this id which identifies the timeout. The ids which will be sent as a parameter to this function are being shared by two functions setTimeout() and setInterval().

How do I stop setTimeout in React?

Clearing setTimeout What is this? To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout(). For example, the code below shows how to properly clear a timer inside of a functional React component.


3 Answers

You need to store the result of setTimeout in a variable, and use clearTimeout to clear that variable, not the function:

var timer;

function foo() {
    $("navigation").observe('mouseover',
        function (event) {
                clearTimeout(timer);
        }
    ).observe('mouseout',
        function (event) {
                timer = setTimeout(bar, 1000);
        }
    );
}

function bar() {
    alert("hi");
}
like image 144
Doug Neiner Avatar answered Oct 22 '22 22:10

Doug Neiner


Because the clearTimeout function take the argument returned by the setTimeout function:

var t = null;
function foo() {
    $("navigation").observe('mouseover',
        function (event) {
            if (t != null) clearTimeout(t);
        }
    ).observe('mouseout',
        function (event) {
            t = setTimeout(bar, 1000);
        }
    );
}

function bar() {
    alert("hi");
}
like image 37
Darin Dimitrov Avatar answered Oct 23 '22 00:10

Darin Dimitrov


See the mozilla docs on window.setTimeout():

setTimeout actually returns a reference which you can use to clear the timeout:

tId = setTimeout(bar, 1000);
clearTimeout(tId);
like image 40
David Snabel-Caunt Avatar answered Oct 23 '22 00:10

David Snabel-Caunt