I have some jQuery code that looks like this:
$('.mainNav2 > li').mouseleave(function(){
var someNum = Math.random();
$(this).attr('id', someNum);
var t = setTimeout("HideMenu(someNum)", 200);
$('li.clicked').mouseenter(function() {
clearTimeout(t);
});
});
function HideMenu(id) {
$('#'+id).removeClass('clicked');
}
It's purpose is to hide a mega menu on mouse leave, but also takes into account accidental mouse leaves, by using a 300 millisecond setTimeout. If the user brings the mouse pointer back into the li within 300 milliseconds, the menu is not hidden because clearTimout(t) is called.
The problem is when the user DOES intent to mouseout, the function in the setTimout is not being called. According to this page: http://www.w3schools.com/js/js_timing.asp my syntax is correct, but I can only get the HideMenu function called from the setTimeout if I write it like this:
var t = setTimeout(HideMenu, 300);
Why isn't it working as written, where I can pass a variable into the function as a parameter?
Example 1: Passing Parameter to setTimeout In the above program, the greet() function is passed to the setTimeout() . The greet() function then gets called after 3000 milliseconds (3 seconds). Hence, the program displays the text Hello world only once after 3 seconds.
Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.
The JS setTimeout() method will call a function after the time specified in milliseconds (1000 ms = 1 second) has passed. The specified function will be executed once.
While the marked correct answer is one method of achieving this... I don't believe it is the correct.
See the attached JS Fiddle: http://jsfiddle.net/PWHw3/
What we are doing here basically is:
setTimeout(function, timeout, param);
Example:
var test = function(a){
var b = (a) ? a : "fail";
alert(b);
};
setTimeout(test, 500, "works");
This works for me, and eliminates the needs to pass through two functions.
This works, and can be used within a loop also.
var x = "OK";
setTimeout(alertOK.bind(null,x), 3000);
x = "Would be WRONG";
console.log("before timeout:", x);
function alertOK(x){
console.log("after timeout:",x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With