Deno Program Lifecycle

Deno Program Lifecycle mainly consists of two events – the load and unload lifecycle events. You can use these events to initialize and clean up code respectively in your program.

Listeners for load events can be asynchronous while listeners for the unload events need to be synchronous.

Both load and unload events cannot be canceled.

Deno Program Lifecycle – Example

You may have a look at the example given on https://deno.land/manual/runtime/program_lifecycle

Main.ts

import "./imported.ts";

const handler = (e: Event): void => {
  console.log(`got ${e.type} event in event handler (main)`);
};

window.addEventListener("load", handler);

window.addEventListener("unload", handler);

window.onload = (e: Event): void => {
  console.log(`got ${e.type} event in onload function (main)`);
};

window.onunload = (e: Event): void => {
  console.log(`got ${e.type} event in onunload function (main)`);
};

console.log("log from main script");

Imported.ts

const handler = (e: Event): void => {
  console.log(`got ${e.type} event in event handler (imported)`);
};

window.addEventListener("load", handler);
window.addEventListener("unload", handler);

window.onload = (e: Event): void => {
  console.log(`got ${e.type} event in onload function (imported)`);
};

window.onunload = (e: Event): void => {
  console.log(`got ${e.type} event in onunload function (imported)`);
};

console.log("log from imported script");

Deno Program Lifecycle – Output

$ deno run main.ts
log from imported script
log from main script
got load event in onload function (main)
got load event in event handler (imported)
got load event in event handler (main)
got unload event in onunload function (main)
got unload event in event handler (imported)
got unload event in event handler (main)

Reference

In the next section, we will be working on a Deno program using vscode editor.