I have created a Queue class in javascript and I would like to store functions as data in a queue. That way I can build up requests (function calls) and respond to them when I need to (actually executing the function).
Is there any way to store a function as data, somewhat similar to
.setTimeout("doSomething()", 1000);
except it would be
functionQueue.enqueue(doSomething());
Where it would store doSomething() as data so when I retrieve the data from the queue, the function would be executed.
I'm guessing I would have to have doSomething() in quotes -> "doSomething()" and some how make it call the function using a string, anyone know how that could be done?
You can also use the .call() method of a function object.
In addition, you can also add the function directly to the queue:
Refer to the function you're storing without the () at the end.
doSomething
is a variable (that happens to be a function);doSomething()
is an instruction to execute the function.Later on, when you're using the queue, you'll want something like
(functionQueue.pop())()
-- that is, execute functionQueue.pop, and then execute the return value of that call to pop.All functions are actually variables, so it's actually pretty easy to store all your functions in array (by referencing them without the
()
):This becomes a bit more complex if you want to pass parameters to your functions, but once you've setup the framework for doing this once it becomes easy every time thereafter. Essentially what you're going to do is create a wrapper function which, when invoked, fires off a predefined function with a particular context and parameter set:
Now that we've got a utility function for wrapping, let's see how it's used to create future invocations of functions:
This code could be improved by allowing the wrapper to either use an array or a series of arguments (but doing so would muddle up the example I'm trying to make).
Here is a nice Queue class you can use without the use of timeouts:
It can be used like so: