JavaScript Deferred Callback Queue

This is a small introduction to our JS deferred callback queue library and the story behind it....

This is a small introduction to our JS deferred callback queue library and the story behind it.

We had a project where we had to optimize the UI. On each keypress, there was a callback to save the state of the form. Naturally, we first tried using a third party library that we knew had the ability to throttle the execution of functions. The first library that came to mind was Underscore.js. After giving it a try, it turned out that the interactions were still slower than we wanted them to be. We tried tweaking the save functionality, but there wasn't much to tweak, as it was a simple ajax call that would send the current state of a VueJS component and send it to an endpoint to store it in Redis so that the user can log in from a different browser and continue their purchase from that page.

With all this in mind, we decided to write our functionality that would delay, defer and throttle the execution of a given callback.

The idea was simple, on each keypress queue the functionality to save with a delay, but if it's already in the queue, reset the delay.

For example:

var queue = new DeferredCallbackQueue(128, true);
function save() {
  alert('saved!');
}
for (var c = 0; c < 128; c++) {
  queue.addCall(save, 512);
}

Run on JSFiddle.net

In this example, a queue is created, with a delay of 128 miliseconds and the worker will autostart.

The queue uses only 1 javascript interval to process it's queue, meaning you can have as many queues as you want, using very few resources.

So instead of seeing 128 alert() boxes on your screen, you will only see 1. You can customize the save() function to do ajax calls or whatever else you'd like it to do, it'll work the same.

You can download this library from npmjs.

Have fun coding!

comments powered by Disqus

Want more awesome stuff?

stay up to date with our articles by signing up to our newsletter