2

I have been searching Google and SO, but I am having a hard time wrapping my brain around this for some reason. Just to emphasize, I do NOT want to load a library like JQuery, since I don't need the majority of it. And while I could use an animation library, I've already built the few functions I need myself (some of them aren't even standard animations you would find in a library), so I'm not sure those would even be helpful. In fact, I could just as easily title this question "How to - Async function queue", since it isn't specific to animation.

In my searching, I have run across the idea of Promises, but that seems like a bit more than I need for this.

I get the general principle - you have an async function that uses setInterval / setTimeout, and given the right condition, you clear the interval (if applicable) and run a callback:

function callback() {
    alert('It was just a sales call... Now where were we?');
}
function anim() {
    var i = 0,
        interval = setInterval( function() {
            // do something with the current value of i
            if (i === 100) {
                clearInterval( interval );
                callback();
            }
            i++;
        }, 50);
}

Of course, this is better if you make it reusable, by making 'callback' an argument of anim(). However, what I truly want to be able to do is the following:

var populateDialog = new Queue([
    {fn: anim, args: ['height','300px',1500]},
    {fn: type, args: [input.value, outputDiv]},
    {fn: highlight}
]);
populateDialog.start();

The first function would be called, and when it's complete, the next item in the queue's array would be called. The problem is, while the queue itself could easily call the functions in order, it needs to know when the current function's status is 'complete' before proceeding.

How do I need to design any function I want to add to the queue so that it either a) publishes its state (and how do I have the queue detect that?) or b) can accept the callback from the queue? I'm guessing the former would involve some sort of custom event system, and that the latter would be easier, and look something like:

function name(callback, param1, param2, ... paramX) {
    // setTimeout or setInterval some stuff, then call the callback argument
}

where the callback is always the first parameter, so that any number of other parameters could be tacked on. But like I said, I am having real trouble wrapping my brain around all of this, so a thorough explanation / any alternatives would be greatly appreciated!

EDIT

The queue that I came up with can be found at my follow-up question.

Community
  • 1
  • 1
Marcus Hughes
  • 1,147
  • 2
  • 14
  • 21

1 Answers1

3

How do I need to design any function I want to add to the queue so that it either a) publishes its state (and how do I have the queue detect that?) I'm guessing it would involve some sort of custom event system

Exactly.

That would be the concept of Promises - your animation function returns an object on which the queue can attach the "done" listener. If you don't want to use one of the many many libraries, you can also implement your own system (a simple pub-once/sub-often pattern). Have a look at How is a promise/defer library implemented? (especially the first two revisions of my answer) for some inspiration…

The queue would then work like

var promise = queue[i].fn.apply(null, queue[i].args);
promise.then(function() {
    i++;
    // … "recurse"
});

b) can accept the callback from the queue? That would be easier, and look something like: function name(callback, param1, param2, ... paramX) {…} where the callback is always the first parameter, so that any number of other parameters could be tacked on.

Exactly. Or the last parameter, which is more common. Have a look at the apply Function method for calling functions with a dynamic number of arguments.

The queue would be something like

function step(i) {
    function callback() {
        step(i+1); // "recurse"
    }
    if (i < queue.length)
        queue[i].fn.apply(null, queue[i].args.concat(callback));
    // else: all done
}

But like I said, I am having real trouble wrapping my brain around all of this, so a thorough explanation / any alternatives would be greatly appreciated!

Well, you've nailed it already - there are no other alternatives than the two methods you outlined. The promise approach is more sound and works better for variadic parameters of the animation functions, while the callback approach is the simpler one.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Yes, I realize callback is usually the last argument, which is why having it first weirded me out. could you edit your answer to show how I would need to have each function access that? I know how to use apply - I could easily add the callback to the parameter array. Do I need to access arguments, and .pop() the last item (the callback)? – Marcus Hughes Aug 22 '13 at 18:16
  • Also, I nailed the concepts. I understand the concept behind it all. I just can't seem to translate that into actual code! Heh. Which of the two methods is better? Pros and cons... which is easier? Honestly, the Promises idea is what really confused me. No matter how many times I read through various articles on it, I could NOT get that sucker figured out! – Marcus Hughes Aug 22 '13 at 18:18
  • Thank you for your added explanation, though I still wasn't sure how to actually implement it until I sat down and figured it out myself. See my edited post to see if I've implemented it well. – Marcus Hughes Aug 26 '13 at 10:20
  • Oh, oK... I didn't know I should do that. As the title of the post suggests, I was wanting a full how-to on making a queue, since I was having trouble finding this elsewhere. While your answer got me on my way, I didn't feel like it was sufficient enough to mark. There's still enough kinks to work out with what I've posted that I felt it still fit under the "how-to" title. If you really think I should start a new question, though, I can do so. – Marcus Hughes Aug 26 '13 at 11:42
  • Yes, I think your new question is basically different. While it may be on the same topic, the question style has dramatically changed (from "*How to design a queue*", "*How to do callbacks*" to "*Does my code have issues*" and "*What features should a queue have*"). – Bergi Aug 26 '13 at 12:19
  • As advised, I am reposting the new material as a new question, and have accepted your answer. I also updated the title slightly to better reflect the more limited scope of this post's topic. – Marcus Hughes Aug 27 '13 at 00:59