javascript - How to correctly call clearTimeout? (Timeout id lost?) -
i trying make simple settimeout, make div tag invisible after 2 seconds.
the settimeout function makes div invisible irregularly, , after 1 sec, , on.
here code:
function begintimeout(){ t = settimeout(function(){hidesubmenu()},2000); } function hidesubmenu(){ var elem; elem = document.getelementbyid("ul_navlist1"); elem.style.visibility="hidden"; cleartimeout(t); }
by way, t global variable. have tried too: t = settimeout("hidesubmenu()",2000);
same irregular results.
update op:
this div contains menu , submenu. edited little bit readable here.
the right_rect div contains menu , submenu. in div call onmouseout hide 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 part of javascript use perform hiding , showing 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 not code.
you can this:
function begintimeout(){ settimeout(hidesubmenu,2000); } function hidesubmenu(){ document.getelementbyid("ul_navlist1").style.visibility="hidden"; }
settimeout()
runs once, no need clear unless want stop executing before does. i'm not sure question you're calling begintimeout()
, time @ it's kicked off may vary. i'd in document load
event of sort or @ end of <body>
, depends else have running.
as side note, put in single statement, this:
settimeout(function() { document.getelementbyid("ul_navlist1").style.visibility="hidden"; }, 2000);
Comments
Post a Comment