0

The following simple example is supposed to print a number in the console after clicking the button. If you click more than once in a short period of time, it will wait until all tasks are finished to print all the results (after calling awaitAll).

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js"></script>
    </head>
    <body>
        <button id="send">Send</button>
    </body>
    <script>
        var button = document.querySelector('#send');
        var q = queue(1);
        var i = 0;
        button.addEventListener('click', function() {
            var message = i++;
            q.defer(function(message, callback) {
                setTimeout(function() {
                    callback(null, message);
                }, 3000);
            }, message);
        });

        q.awaitAll(function(err, result) {
            console.log(result);
        });
    </script>
</html>

This works as intended. However, what happens if I want to reuse the queue again? For example, click on the button once and it will print [0]. Then click again and it will print [0,1]. The queue will keep track of previous tasks even after q.awaitAll has been called. I guess that could be useful but I have some concerns when the user provides tasks to the queue and after calling the callback, q.awaitAll outputs an array with all the previous results. The user probably needs the last one and returning everything seems a bit wasteful.

Is there some way to reset the queue?

By the way, I don't want to do this:

   button.addEventListener('click', function() {
    var q = queue(1);
    var message = i++;
    q.defer(function(message, callback) {
        setTimeout(function() {
            callback(null, message);
        }, 3000);
    }, message);
});

Here the queue doesn't work. In this case, I would be able to click several times and generate many queues running simultaneously.

Thanks

r_31415
  • 8,752
  • 17
  • 74
  • 121
  • Not certain interpret Question correctly ? What is expected result ? – guest271314 Aug 22 '15 at 06:26
  • I was expecting that after each click, the queue would return only the current tasks (e.g. after the first click: [0], after the second click: [1] and so on) – r_31415 Aug 22 '15 at 06:28
  • Tried jQuery `.queue()` http://api.jquery.com/queue ? – guest271314 Aug 22 '15 at 06:30
  • I don't think that implementation intends to work as a general purpose queue. – r_31415 Aug 22 '15 at 06:33
  • _"I don't think that implementation intends to work as a general purpose queue."_ See http://api.jquery.com/jquery.queue Should be able to be utilized for general purpose ; see http://stackoverflow.com/questions/32028368/execute-function-queue-in-javascript ? – guest271314 Aug 22 '15 at 06:36
  • They are using mainly $.Deferred. That's not what I want. – r_31415 Aug 22 '15 at 07:03

0 Answers0