Using clearTimeout to cancel a timeout event

19,704

Solution 1

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");
}

Solution 2

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");
}

Solution 3

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);
Share:
19,704

Related videos on Youtube

Rich
Author by

Rich

Updated on April 19, 2022

Comments

  • Rich
    Rich about 2 years

    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");
    }
    
  • Doug Neiner
    Doug Neiner over 14 years
    Hey, no problem. Be sure to mark the answer solved by choosing one of the answers as the "accepted" solution.
  • Arturo Hernandez
    Arturo Hernandez about 11 years
    I actually had a problem when the timer variable was not global. I had to use window.timer; I suggest you expand on your answer.