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