Event-Based Programming: What Async Has Over Sync

Using promises, eventing, or named functions eliminates the nasty callback hell

One of JavaScript’s strengths is how it handles asynchronous (async for short) code. Rather than blocking the thread, async code gets pushed to an event queue that fires after all other code executes. It can, however, be difficult for beginners to follow async code. Jonathan Creamer will help clear up any confusion you might have in this article.

 

JavaScript’s most basic async functions are setTimeout and setInterval. The setTimeout function executes a given function after a certain amount of time passes. It accepts a callback function as the first argument and a time (in milliseconds) as the second argument. Here’s an example of its usage. As expected, the console outputs “a”, “b”, and then 500 ms(ish) later, you see “c”, “d”, and “e”. Jonathan Creamer uses “ish” because setTimeout is actually unpredictable. In fact, even the HTML5 spec talks about this issue: “This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.” Interestingly, a timeout will not execute until all of the remaining code in a block has executed. So if a timeout is set, and then some long running function executes, the timeout will not even start until that long running function has finished.

Comments

Be the first to write a comment

You must me logged in to write a comment.