[removed] how to pass parameters to callback funct

2019-01-07 00:22发布

This question already has an answer here:

I'm stumped on how to correctly pass parameters to a callback function without immediately calling that function.

For example, this will work as expected:

var callBack = function() { ... }
window.setTimeout( callBack, 1000 );

But this will accidentally call callBack:

var callBack = function(param1, param2) { ... }
window.setTimeout( callBack('foo','bar'), 1000 );

2条回答
时光不老,我们不散
2楼-- · 2019-01-07 00:58

You can call it as follows,

var callBack = function(param1, param2) { ... }
window.setTimeout( function(){callBack('foo','bar');}, 1000 );
查看更多
倾城 Initia
3楼-- · 2019-01-07 01:02

The way to pass parameters is after the time parameter as is stated in the documentation of settimeout().

var timer = window.setTimeout( func, delay, [ param1, param2, ... ]

The first argument is the actual callback, the second is the time in miliseconds and the last (optional) argument is an array of parameters to pass to the callback.

So, for your example it would be something like:

window.setTimeout( callBack, 1000, [ "foo", "bar" ] );

The title of your question is slightly misleading as the method used to pass parameters to a callback function differs in the implementation of the code that is using it. As you might imagine, the actual function object and it's parameters don't necessarily need to be passed together as the functions execution is deferred to a later time; Only then do the parameters need to come in contact with the callback.


For a more generic explanation of how to pass arguments to a callback object you can take a look at this post: JavaScript: Passing parameters to a callback function.

查看更多
登录 后发表回答