How to pass parameters when calling a function without the parenthesis [Javascript]

*爱你&永不变心* 提交于 2019-12-05 06:07:26
setTimeout(function() { tryMe(parm1, parm2); }, 200);

A more robust offering, to ensure that the values of parm1, parm2 don't change before the timeout fires (per @lincolnk's comment):

setTimeout(function() {
   var p1 = parm1;
   var p2 = parm2;
   tryMe(p1, p2);
}, 200);

@patrick dw, you're right, has to be evaluated before.

You can wrap tryMe in a closure.

For example:

var f = function(){tryMe('some parameter');};
setTimeout(f, 200);

Here, we create a function object, f, which calls tryMe with the desired parameter(s). Then we pass f to setTimeout. When the timeout expires, f will be called, which will in turn call tryMe with the desired parameters.

A word of warning if you wish to pass in parameters that may change before the timeout gets called (for example, if you are setting several timeouts in a for loop): you will want to bind those variables like so:

var f = function(someParamter){return function(){tryMe(someParameter);};};
setTimeout(f(someParameter), 200);

The reason simply doing something like

setTimeout(tryMe('some parameter'), 200); //Does not work.

doesn't work is because you are passing the result of evaluating tryMe instead of the function object tryMe itself.

You are not calling the function, the browser does - after 200 milliseconds. You are merely providing it with the function that needs being called. Firefox actually allows specifying additional parameters in the setTimeout call:

setTimeout(tryMe, 200, "first parameter", "second parameter");

However, as far as I know no other browsers support this feature so you should really use a closure function as explained by other answers already. Here you create a temporary function with the sole purpose of calling your original function with the right parameters.

setTimeout(function() {tryMe("first parameter", "second parameter")}, 200);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!