Not All Tasks Created Equal!

All programs are seen as composed of control structures, ordered statements, or subroutines, executed in sequence.

function task(id) {
  console.log("Task " + id);
}

task(1);
task(2);
task(3);
task(4);

What will happen when one task (subroutine) takes a long time to complete?

function task(id) {
  console.log("Task " + id);
}

function longtask(id) {
  console.log("Task " + id + " started!");
  for(let i = 0; i < 3e9; i++) {
    // do something!
  }
  console.log("Task " + id + " finished!");
}

task(1);
longtask(2);
task(3);
task(4);

The long (resource intensive) task appears to block the ones that follow!

What are the implications of this for event-driven applications such as web apps?

Well, as long as the "long task" is running, all other things are blocked! The web app will appear unresponsive or frozen!

Example

For example, YouTube loads the video content as you view it. This task is a resource-intensive process, in particular over a slow network. If it were to block other tasks/processes until it has finished, you would not be able to do any of the following while the video content is loading:

  • Like the video
  • Leave a comment or even scroll through the comments
  • Maximize/minimize
  • Change the volume
  • Use any of the controls (play, pause, etc.)
  • ...

But this is not how YouTube works!

So what is the secrete? How does it perform a resource-intensive task such as streaming a video while the web page remains perfectly responsive?!