Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() and setting parameters

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?

like image 763
Ben Avatar asked Mar 02 '11 14:03

Ben


People also ask

How do I pass parameters in setTimeout?

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.

What are the two parameters of the setTimeout function?

Developers generally pass only two parameters to setTimeout method — the callback function and the timeout period.

How many times does setTimeout () execute the function parameter?

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.


2 Answers

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.

like image 134
Roi Avatar answered Nov 15 '22 22:11

Roi


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);
}
like image 36
Lovro Avatar answered Nov 15 '22 22:11

Lovro