• Home
  • blog
  • How to Schedule Background Tasks in JavaScript

How to Schedule Background Tasks in JavaScript

If you remember nothing else about JavaScript, never forget this: it blocks.

Imagine a magical processing pixie makes your browser work. Everything is handled by that single pixie whether it’s rendering HTML, reacting to a menu command, painting on the screen, handling a mouse click or running a JavaScript function. Like most of us, the pixie can only do one thing at a time. If we throw many tasks at the pixie, they get added to a big to-do list and are processed in order.

Everything else stops when the pixie encounters a script tag or has to run a JavaScript function. The code is downloaded (if required) and run immediately before further events or rendering can be handled. This is necessary because your script could do anything: load further code, remove every DOM element, redirect to another URL etc. Even if there were two or more pixies, the others would need to stop work while the first processed your code. That’s blocking. It’s the reason why long-running scripts cause browsers to become unresponsive.

You often want JavaScript to run as soon as possible because the code initializes widgets and event handlers. However, there are less important background tasks which don’t directly affect the user experience, e.g.

  • recording analytics data
  • sending data to social networks (or adding 57 ‘share’ buttons)
  • pre-fetching data
  • pre-processing or pre-rendering content

These are not time-critical but, in order for the page to remain responsive, they shouldn’t run while the user is scrolling or interacting with the content.

Continue reading %How to Schedule Background Tasks in JavaScript%