开发者

Javascript: clearTimeout seems to only suspend, not reset or clear?

开发者 https://www.devze.com 2023-01-17 18:25 出处:网络
I am very new to JS and am trying to modify the JavascriptKit jQuery-based megamenu system to delay showing the menu until the mouse has been hovering over the anchor object for a specified time.

I am very new to JS and am trying to modify the JavascriptKit jQuery-based megamenu system to delay showing the menu until the mouse has been hovering over the anchor object for a specified time.

The problem I am facing right now is that it seems that the clearTimeout that is called on mouseout only suspends the setTimeout, rather than canceling, clearing, resetting it.

At this point I am just showing an alert after a setTimeout call. Currently I have the timeout interval set to 2000 for testing.

As an example, since I have it set to 2 seconds d开发者_C百科elay right now, if I mouse over the object 4 times for 1/2 second, the 5th time I mouse over the object my test alert box appears instantly.

I thought clearTimeout was supposed to completely destroy the timed event. Why does it appear to only pause the countdown?

teststuff:function(){
    if(jkmegamenu.toggletest==1)
     {
         jkmegamenu.executetimedcommand()
         jkmegamenu.toggletest=0
     }
    else
     {
         //jkmegamenu.executetimedcommandcancel()
         clearTimeout(jkmegamenu.teststuff);
     }
    },

    executetimedcommand:function(){
        if(jkmegamenu.toggletest==1)
        {
            alert('abcde')
        }
    },

    canceltimedcommand:function(){
    clearTimeout(jkmegamenu.teststuff);
},


clearTimeout takes a timer id as a parameter, not a function reference.

for example, if you're setting a timeout for jkmegamenu.teststuff, you would do it like this

// set the delayed call
var timerID = setTimeout(jkmegamenu.teststuff, 2000);

// cancel it
clearTimeout(timerID);
timerID = 0;


You're defining "teststuff" as a function, and then passing it to clearTimeout(). What you pass to clearTimeout() should the variable returned from setTimeout(). If you're assigning the return value of setTimeout() to "teststuff", then you redfine it, you won't be able to pass the original value to clearTimeout().

0

精彩评论

暂无评论...
验证码 换一张
取 消