Search code examples
javascriptprototypejsdom-events

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

Solution

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