callback function(回呼函數)
回呼函數 (Callback Function)
A Function you give to another function, to be run when the other function is finished.
So the function you call(i.e. invoke), ‘calls back’ by calling the function you gave it when it finishes.
你呼叫一個函數並給它一個函數,當該函數結束時,那個函數回呼你給它的函數。簡單來說 callback function 與一般函數最大差別就是呼叫方式不同。
- 非同步運setTimeout函數:
等原本函數離開執行堆疊後,到了設定秒數才從執行佇列被拉出來執行。
function sayHiLater() {
var greeting = ‘Hi’;setTimeout(function () { //會在執行佇列,等其他函式都執行完畢才執行
console.log(greeting)}, 3000)}sayHiLater() // Hi
3000毫秒過後,引擎會看有沒有函數在等待,並發現執行佇列中的函式進行執行,但 greeting 不在函數裡,於是往外層尋找,此時 sayHiLater 已經結束了,但因為閉包的特性,記憶體空間中的 greeting 能夠被取用,console.log的值因此為 ’Hi’。
- 事件監聽函數:
在設定的事件被觸發後才會執行裡面的函數。
$(‘button’).click(function(){ })
- 典型的callback function:
利用 一級函數 的特性,函數被當作參數傳入其他函數中,並在其他函數被觸發執行後才被呼叫。
function tellMeWhenDone(callback){
var a=1000;
var b=2000; callback(); }tellMeWhenDone(function(){console.log(‘I am done’) })