Skip to content

J060 Usage of Callback Methods

An assignment to understand the basics of callbacks and various ways to declare functions in ES (ECMAScript).

Within your app.js:

Task 1:

Start by copying the following function into app.js.

function job(func) {
  console.log("start");
  // This is an inefficient way to simulate a delay,
  // but for the purpose of keeping the code synchronous,
  // it's simple and understandable.
  for (var i = 0; i < 1000000000; i++) {}
  func();
  console.log("end");
}

This function can be invoked with another function, which will be executed after a short delay (approximately 2 seconds). Your task is to call the job function in such a way that a * is printed to the console after the 2-second delay.

Invoke the job function using:

  1. A reference to a predefined function.
  2. An anonymous function.
  3. An arrow function (lambda).
Solution
"use strict";

function job(func) {
  console.log("start");
  for (var i = 0; i < 1000000000; i++) {}
  func();
  console.log("end");
}

// Using a reference to a predefined function
function printStar() {
  console.log('*');
}
job(printStar);

// Using an anonymous function
job(function() {
  console.log('*');
});

// Using an arrow function (lambda)
job(() => console.log('*'));