❗ Events and Callbacks

Lesson

❗ Events and Callbacks

An event is an action which triggers the code to do something – usually an event will trigger a function. Events include actions such as clicking the mouse or pressing a key. We can link certain events to trigger certain actions, for example pressing the arrow keys may trigger a sprite to move side to side.

You might remember events from Scratch…

To make anything happen, we need to use events. Using the mouse to click the green flag on Scratch or the ‘run’ button on repl.it is an event.

Javascript is an event-based language, just like Scratch. This means it keeps working while listening for other events, instead of waiting for a response before moving on. Because of this, multiple things can be happening at the same time.

Why are events useful?

Events allow us to make things happen. They are essential for creating interactive code, like in Scratch games or on websites.

What is a callback?

Callbacks are event-driven. When an event happens, a function is called and its code is executed.

Just like when we call on a function to run the code we’ve declared within it, we can use a function (which is linked to an event) to call another function. This is called a callback.

function sumComplete(){
  alert('Numbers have been added together.');
}

function functionAdd(a,b, callback){
  alert('These two numbers added =', a + b);
  callback();
}

functionAdd(10,20, sumComplete);

//These two numbers added = 30
//Numbers have been added together.

The console will print the messages in this order because the ‘callback’ inside functionAdd tells the sumComplete function to run.

We wouldn’t want the sumComplete function to run before functionAdd, so even though we have declared sumComplete first, it is only executed once it has been called as part of functionAdd.

Why are callbacks useful?

Callbacks are a way to make sure that our code runs in the order we want it to, and that functions don’t execute before the required event triggers them. For example, we don’t want our sprite in Scratch to move to the right before we’ve pressed the arrow key.

Try It Out

Try this functions and callbacks treasure hunt:

@

Not recently active