Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout with arguments

Tags:

javascript

having a bit of a headache on trying to work this out. What I want to do is have a custom setTimeout with arguments with out having to create a function to pass it. Let me explain by code:

Want to avoid:

function makeTimeout(serial){
  serial.close();
}

setTimeout(makeTimeout(sp.name), 250);

what I want to do is somehow just call a 1 liner by like:

setTimeout(function(arg1){ .... }(argument_value), 250);

Can this be done or can you only pass in a no argument function?

like image 669
Menztrual Avatar asked Sep 17 '12 00:09

Menztrual


People also ask

How do you pass arguments to setTimeout?

You can pass the parameter to the setTimeout callback function as: setTimeout(function, milliseconds, param1, param2, ...) eg. Yeah!

How many arguments will setTimeout take?

Bookmark this question. Show activity on this post. This SO answer makes a call to setTimeout with four arguments.

What is third argument in setTimeout?

Starting from the (optional) third argument, you can specify an arbitrary number of arguments to the JavaScript setTimeout() method, which are all passed through to the provided timeout callback function. For example: function timeoutFunc(... args){ console.


2 Answers

You can pass it an anonymous function that invokes makeTimeout with the given arguments:

setTimeout(function () {
  makeTimeout(sp.name);
}, 250);

There's also an alternative, using bind:

setTimeout(makeTimeout.bind(this, sp.name), 250);

This function, however, is an ECMAScript 5th Edition feature, not yet supported in all major browsers. For compatibility, you can include bind's source, which is available at MDN, allowing you to use it in browsers that don't support it natively.

DEMO.

like image 152
João Silva Avatar answered Oct 21 '22 09:10

João Silva


If you don't want to declare a separate function, you can use an immediately invoked function expression and closure, e.g.

// Parameter to use
var bar = 'bar';

// Function to call
function foo(arg) {
  alert(arg);
}

// Go…
setTimeout(
  (function(arg1){
    return function(){
      foo(arg1);
    };
  }(bar)), 2000);

Alternatively, you can use the function constructor:

setTimeout( Function('foo(bar)'), 2000);

Or you can use a string:

setTimeout('foo(bar)', 1000);

which is essentially the same thing. Now wait for howls of "but that's like using eval, and everyone knows eval is evil and a massive security breach — all your firstborn are doomed!"

But seriously, eval (and the Function constructor) are inefficient and can lead to lazy programming, so use another option, such as the first above.

like image 33
RobG Avatar answered Oct 21 '22 09:10

RobG