Monday, September 10, 2012

Asynchronous execution pattern

Before we go thought this pattern, lets cover some basic notes about JavaScript timers:

1. There two kinds of timers in JavaScript:
  • setTimeout
  • setInterval
2. Both take two arguments, a function to invoke and a delay period
3. setTimeout will execute the function once
4. setInterval will execute continuously with the specified delay between each execution
5. Delays < 4ms will be bumped to 4ms
6. Important: Timers wont start until the outer most function is finished

Browsers are typically single threaded, they either update the UI or executing JavaScript. Long running JavaScript blocks the UI and browser is unresponsive.

Splitting long-running code over setTimeout blocks releases the thread:

  • While processing a loop limit the scope to a small time window
  • Ensure that there is enough of a gap between timeouts restarting

So let's see a basic example:

So, this is very trivial example, but it's very common scenario in web applications when we gather data through ajax. The problem which can arise is that we don't know how long the process will take, or on low power devices such as mobiles or tablets processing this array could take a lot longer than we would like and UI can stop responding.

One way we can get around this is to create a function which will allow us to defer the execution on multiple periods of time:

No comments:

Post a Comment