MyLeoNes™

Events make programs react — Computing, 7–10 years

An event is something that happens, such as a key being pressed or a character being clicked. It can start a response at the right moment.

Waiting for something to happen

An event is a happening that a program can notice, such as a key press, a mouse click or a sound from a sensor. The program then starts the response connected to that event. This lets an interactive program wait instead of doing everything at once.

Why events are needed

A game cannot know exactly when a player will press a key, so it must be ready to notice that moment. Events were used to connect unpredictable happenings with planned actions. Without them, a button would not know when to respond to a click.

A button that changes colour

First, place a blue button on the screen. Next, attach the event “when this button is clicked” to the action “change colour to yellow”. When the user clicks, the event is noticed and the action runs. A second click can start another action, such as changing it back to blue.

The trap: starting too early

A common mistake is to put the response in the main program so it happens immediately, instead of attaching it to the event. The action may look correct, but it runs before anyone clicks or presses anything. This is reasonable because the action is visible in the code, while its timing is easy to overlook.

Where it helps

Buttons in apps use click events, and games use key or controller events to move characters. Doorbells respond to a press, while some lights respond to movement detected by a sensor. In each case, something happens first and a device reacts to it.

Keep exploring

Other languages

Loading MyLeoNes™…