In user interface programming, most platforms have a concept of a main UI thread, and at least one background thread. This provides the ability to perform long running tasks in the background without preventing the user from interacting with your application.

Web pages are different from other platforms since javascript is a traditionally single threaded language. Instead, blocking operations are performed asynchronously, and their results are typically deferred to another function for later processing. However, excluding I/O operations, this still technically limits a web page to performing one task at a time and could potentially block user interaction if run long enough.

The solution (tl;dr)

There are two ways to get around this problem in javascript. If your task is flexible enough to divide into smaller subtasks, you can use the setTimeOut() function recursively to allow the browser to perform other tasks before moving on to its next subtask. However, many modern browsers also allow the web page to effectively create background threads through the use of Worker() api. Although web workers can be simpler and yield greater performance, they aren’t compatible with older browsers.

Example – Calculating factorial

The following code illustrates two examples of calculating the factorial of a number without blocking the UI thread. It also illustrates how much longer a function may take to run if it’s split into subtasks with setTimeout. You can also view a demo of this code running in action.