Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

js Function queue

js Function queue

Problem

So essentially what I'm trying to do is have a Queue of functions that I can add to. These functions are suppose to be drawing things to a canvas like in an requestAnimationFrame.

What I've tried:

var drawQueue = [];
function animate() {
    while (drawQueue.length !== 0) {
        drawQueue.shift()();
    }
    requestAnimationFrame(function () {
        animate();
    });
}

With that I was trying to add things like:

drawQueue.push(drawthing(0,0,0,0));

this would just run the function and push undefined to the array, this does how work if you just do this:

drawQueue.push(function () {
    console.log("derp");
});

or

drawQueue.push(functionName); //with no args

The but problem here is that I need to pass arguments to most of the functions I'm calling.

my Second attempt:

var drawQueue = [];
function animate() {
    while (drawQueue.length !== 0) {
        var data = drawQueue.shift();
        Object.apply(data.func, data.args);
    }   
    requestAnimationFrame(function () {
        animate();
    }); 
}

while adding function to the queue like:

drawQueue.push({func: functionName, args: [0,0,0,0]});

but I couldn't get that to work either, not 100% how to use Object.apply() and what exactly its doing...

So my question is how do I go about making my function queue or is there a better way to do this?

Problem courtesy of: dabarnes

Solution

You can't add something to the queue like this:

drawQueue.push(drawthing(0,0,0,0));

All that is doing is calling drawthing(0,0,0,0) immediately and pushing the return result from executing the function into the queue.


Instead, you need to push an actual function into the queue like this:

drawQueue.push(function() {drawthing(0,0,0,0)});

If you want to just push the function and arguments into the queue separately like this:

drawQueue.push({func: functionName, args: [0,0,0,0]});

Then, you can pull an item off the queue and execute it like this:

var item = drawQueue.shift();
item.func.apply(this, item.args);

When you call function.apply(a, b), it sets the this ptr to the first argument a and then calls the function with whatever arguments are in the b array.

Solution courtesy of: jfriend00

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

js Function queue

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×