HTML and CSS Reference
Implementing a Main Loop in Dart
John McCutchan, Software Engineer, Google
At the heart of your favorite games is the game loop. At the core of the game loop is control over the game clock.
In each frame the game does some or all of the following: updates the game state, triggers timers, processes user inputs,
renders graphics, and plays audio. Each of these operations must be synchronized using a virtual clock controlled by
the game loop. This chapter explains how to implement a deterministic and efficient main loop for any type of game
designed from the ground up to run in the browser.
This chapter uses the Dart programming language ( www.dartlang.org/ ) for reference code but the focus of this
chapter is not on Dart. Dart should be familiar to programmers coming from languages like Java or C#, and the code does
Implementing a main loop must be done with respect to the browser's execution model. The Dart program
cannot execute endlessly; it must yield control back to the browser every frame. User inputs are delivered via
asynchronous event callbacks and the rendering is synchronized with the browser by performing rendering in the
User inputs are delivered as discrete events through callbacks registered with the browser. The browser delivers a
different input event per device type. For example, there are four separate event sources for key down, key up, mouse
button down, and mouse button up. The main loop should record all user inputs into a single stream of input events
between frames, allowing input code to process all inputs in one location. Processing complex user inputs like chords
or sequences will be covered as well.
When you finish this chapter you will be able to build a robust, reusable, main loop upon which you can build games.
The source code included with this chapter is written in Dart. Dart is an object-oriented programming language that
machine (VM). Even though the source code is written in Dart, the focus of this chapter is on the main loop for games,
and the concepts, design, and algorithms discussed in this chapter do not depend on Dart functionality.
Dart is an object-oriented programming language designed to be familiar to programmers coming from