w3resource

JavaScript delayed callback function - Invoke Callback after a specific second

JavaScript Asynchronous: Exercise-1 with Solution

Write a JavaScript function that takes a callback and invokes it after a delay of 2 second.

Sample Solution:

JavaScript Code:

function invokeAfterDelay(callback) {
  setTimeout(callback, 2000); // 2000 milliseconds = 2 second
}
function display_message() {
  console.log('Hello!');
}
invokeAfterDelay(display_message); // Invokes the sayHello function after a 1-second delay

Output:

"Hello!"

Note: Executed on JS Bin

Explanation:

In the above exercise JavaScript function "invokeAfterDelay()" takes a callback and invokes it after a delay of 2 second (2000 milliseconds) using the "setTimeout()" function.

In the above function, the "display_message()" function will be invoked after a delay of 2 seconds.

Flowchart:

Flowchart: Invoke Callback after a specific second.

Live Demo:

See the Pen javascript-asynchronous-exercise-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Asynchronous Exercises Previous: JavaScript Asynchronous Exercises Home.
Asynchronous Exercises Next: Callback to Promise | Transforming asynchronous functions.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.