20

I want to do what setTimout does, manually, with no timeout.

setTimeout(function,0,args);

Just call a function and pass it an array of arguments, without knowing or caring how many arguments were there.

Basically I want to proxy the function call through another function.

I'm bad with terminology, sorry.

somedev
  • 1,053
  • 1
  • 9
  • 27
  • 1
    See also: http://stackoverflow.com/questions/1881905/call-function-with-multiple-arguments – Christian C. Salvadó Dec 17 '09 at 19:19
  • @Michał Perłakowski not sure how this is a duplicate (already answered) by the link you added since it was asked and answered first? Maybe you're just saying "cleared question here" ? – somedev Mar 27 '17 at 19:10
  • @somedev The other question has better answers, see [Should I flag a question as duplicate if it has received better answers?](https://meta.stackoverflow.com/q/251938/3853934) – Michał Perłakowski Mar 28 '17 at 08:58
  • @MichałPerłakowski I figured, was just curious – somedev Mar 28 '17 at 14:42

4 Answers4

44
function f(a, b, c) { return a + b + c; }
alert(f.apply(f, ['hello', ' ', 'world']));
just somebody
  • 18,602
  • 6
  • 51
  • 60
7

In ES6:

function myFunc(a, b, c){
    console.log(a, b, c);
}

var args = [1, 2, 3];
myFunc(...args);
Nainemom
  • 143
  • 1
  • 2
  • 8
0

Sounds like you want a function with variable arguments as an argument. The best way to do this is either an explicit Array or object in general.

myFunction(callbackFunction, count, arrayOfOptions);

myFunction(callbackFunction, count, objectOfOptions);
Darrell Brogdon
  • 6,843
  • 9
  • 47
  • 62
0

Take a look at javascript's arguments variable. This is an array of all arguments passed in to the function.

So you can create your core function like this:

f = function () {
    for (arg in arguments) {
         // do stuff
    }
}

Then, create a new function with the right arguments:

f2 = function () {
    return f(arg1, arg2, arg3 /* etc. */);
}

And pass this function to setTimeout:

setTimeout(f2, 0);
groovecoder
  • 1,551
  • 1
  • 17
  • 27
Seth
  • 45,033
  • 10
  • 85
  • 120