How it works

You might now be concerned about how often the render function is executed. Let me reassure you, it is only executed whenever the virtual DOM might have changed, not 60 times per second. It is also never called more than once per frame (16ms).

The projector is responsible for updating the DOM. It works as follows:

  1. The projector waits until its scheduleRender() function gets called one or more times.
  2. The projector waits until the browser signals it is ready to paint the next frame (using requestAnimationFrame).
  3. The projector calls the render function to render the virtual DOM.
  4. The projector determines the differences between this virtual DOM and the previous one.
  5. The differences are applied to the real DOM, applying animations if specified.

You may have noticed that we did not call scheduleRender() in our previous assignment. So how did the projector know it needed to render the DOM? The answer is that scheduleRender() is called automatically every time an event handler registered on the virtual DOM is invoked. So in our previous assignment, the oninput event handler caused the projector to render.

So why is this important? Because if you make changes to the data by other means than through a registered event handler, you must not forget to call scheduleRender(). Common scenario's where this happens are:

  • Data is received from the server (using XHR or websockets)
  • Code is executed asynchronously using setTimeout, setInterval or requestAnimationFrame. (Note: not needed when using Promises or MutationObservers)

In your next example, you will see an attempt to make the flying saucer orbit a planet. However, it does not work as it should. You must use the information you just received to fix the broken example.

Press next to start. Good luck.