Most Angular developers are probably already familiar with the $timeout service. This service serves an important role in Angular 1.x, so today I decided to go digging for its counterpart in the new Angular world.
Now, how does this work in post 1.x Angular?
I initially thought the approach would be very similar. I stumbled upon a class called TimerWrapper that I thought would be the answer to this. However, after tweeting to Angular member Viktor Savkin I learned that TimerWrapper is part of the internal API. He also told me we no longer need to worry about kicking off digest cycles manually when dealing with window.setTimeout. Instead zone.js will do it for us, which means we can go back to using regular window.setTimeout. I will have to learn more about zone.js at a later time since this is a new concept to me.
To have some fun with setTimeout I decided to use it to animate an implementation of the insertion sort algorithm. Insertion sort is one of the simple algorithms you may remember from your CS data structures curriculum, but if you don't, that's ok for the purposes of this article :-)
The idea is to use setTimeout to delay object updates as the algorithm shuffles through the array as the sort executes. As an element is shuffled I give it a different background color until the next element is shuffled. As always I have a live demo of this, but the UI looks something like this:
I won't cover the details of Insertion sort here, but in the source code below you can see how I have integrated setTimeout in the shuffling stage of the algorithm.
window.setTimeout() takes a lambda expression and a timeout in milliseconds representing the execution delay.