Callback Function
把函式當作另一個函式的參數,透過另一個函式來呼叫它,他可以「控制多個函式間執行的順序」。
來看個例子,首先定義兩個 function ,因為 function 會立即執行,所以先印出 1 ,在印出 2 :
1 2 3 4 5 6 7 8 9
| function first(){ console.log(1); } function second(){ console.log(2); } first();
second();
|
透過 setTimeout 讓 first() 設定延遲 500毫秒 在執行, JavaScript 不會等待 first() 執行完才執行 second() ;所以就算我們先呼叫了 first() ,也會是 second() 先被執行,結果就會是先印出 2 ,在印出 1 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function first(){ setTimeout( function(){ console.log(1); }, 500 ); } function second(){ console.log(2); } first();
second();
|
像這種時候,為了確保執行的順序,就會透過 Callback function 的形式來處理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
var first=function(callback){
setTimeout(function(){ console.log(1); callback(); }, 500); };
var second=function(){ console.log(2); };
first(second);
|
像這樣,無論 first 在執行的時候要等多久, second 都會等到 console.log(1); 之後才執行。
另一個例子:
1 2 3 4 5 6 7 8 9 10 11
| function doHomework(subject, callback) { alert(`Starting my ${subject} homework.`); callback(); } function alertFinished(){ alert('Finished my homework'); }
doHomework('math', alertFinished);
|
不過需要注意的是,當函式之間的相依過深,callback 多層之後產生的「Callback Hell」維護起來就會很複雜。
參考文獻
https://ithelp.ithome.com.tw/articles/10192739
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced