JavaScript - callback function

  1. 1. What is
  2. 2. Why need
  3. 3. How to
  4. Reference

1. What is

  • A function that is to be executed after another function has finished executing – hence the name call back
  • In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.

2. Why need

JS is an event driven language, instead of waiting for a response before moving on, JS will keep executing while listening for other events.

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}

function second(){
  console.log(2);
}

first();
second();

// 2, 1

The above example shows JS didn’t wait for a response from first() before moving on to execute second()

3. How to

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}

doHomework('math', function() {
  alert('Finished my homework');
});

Reference

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 stone2paul@gmail.com

文章标题:JavaScript - callback function

文章字数:161

本文作者:Leilei Chen

发布时间:2020-01-31, 12:57:57

最后更新:2020-02-02, 14:06:57

原始链接:https://www.llchen60.com/JavaScript-callback-function/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏