Read my book

I wrote books about Webpack and React. Check them out!

Monday, November 22, 2010

JavaScript - Abstracting Interval Based Progress Monitor

In the previous post I showed you how to exploit JavaScript's interval to create a non-blocking loop. This allows to render dialog/whatnot while you are doing some heavy number crunching.

As I began to use the solution in larger scale I noticed it's possible to abstract it a bit. In this post I am going to show how I did that. In the process you might be able to learn something about callbacks and the decorator pattern.

Problem

Last time we ended up with a processing function like this:



The problem is that it really isn't fun to write that snippet each time you want to process something asynchronously. In order to deal with this issue I abstracted the code a bit as can be seen next.

Solution

Here's the solution I came up with:



Note how I extracted the core logic in "loop" function. It handles dealing with interval while you can focus only on setting up the callback function properly. The callback uses return value to communicate whether or not to continue executing the loop.

I used the decorator pattern within the implementation of "loop". In this case I use "cycle" function to encapsulate the passed callback to curry it with some extra functionality.

Conclusion

I guess that was it this time. Hopefully you picked up something from the snippets. Till the next time! :)