How to call clearTimeout correctly? (Timeout ID lost?)

I am trying to make a simple setTimeout to make the div tag invisible after 2 seconds.

The setTimeout function makes the div invisible but irregular, sometimes right away, sometimes after 1 second, etc.

Here is my code:

  function beginTimeOut(){

    t = setTimeout(function(){hideSubMenu()},2000);

}

function hideSubMenu(){
    var elem;
    elem = document.getElementById("ul_navlist1");
    elem.style.visibility="hidden";
    clearTimeout(t);

}

By the way, t is a global variable. I also tried this: t = setTimeout("hideSubMenu()",2000);but with the same irregular results.

UPDATE from OP:

This is the div that contains my menu and submenu. I edited it to be a bit readable here.

Right_rect is a div containing a menu and submenu. In this div, I call onmouseout to hide the submenu.

<div class="right_rect"  onmouseout="beginTimeOut();">      
        <div class="menu2" >
            <ul >
            <li onclick="hideOrShow();"><a href="#">item1</a></li>
                </ul>
        </div>

    <div id="ul_navlist1">
        <ul >
                    <li><a href="#">sub_item1</a></li>
            </ul>
        </div>      
</div>

and this is the javascript part that I use to hide and show the process.

function hideOrShow(){
    var hOrV;
    var elem;
    var styleType = "visibility";
    elem = document.getElementById("ul_navlist1");
    hOrV = getStyle(elem, styleType);
    if(hOrV =="hidden"){
        //alert();
        elem.style.visibility="visible";
    }else{
        elem.style.visibility="hidden";
    }
}

function beginTimeOut(){
    setTimeout(function(){document.getElementById("ul_navlist1").style.visibility="hidden";}, 2000);

}

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

The getStyle function is not my code.

+3
2

:

function beginTimeOut(){
  setTimeout(hideSubMenu,2000);
}

function hideSubMenu(){
  document.getElementById("ul_navlist1").style.visibility="hidden";
}

setTimeout() , , . , beginTimeOut(), . - load <body>, , .

, :

setTimeout(function() {
  document.getElementById("ul_navlist1").style.visibility="hidden";
}, 2000);
+2

, , -, . , beginTimeout ? Nick Craver, , , -.

, , , setInterval/setTimeout, , . , :

var t=setInterval(function(){doStuff(t)},1000)

. .

+1

Source: https://habr.com/ru/post/1743264/


All Articles