回调和异步
// 回調函數:一個函數中調用傳入的另一個函數
// 這里的callback就是個回調函數
function we(callback,something){something+=" is cool";callback(something);
}function learn(something){console.log(something);
}we(learn,"node.js"); //第一種方式是傳入一個實名函數進行回調we(function(something){ //第二種方式是傳入一個匿名函數進行回調console.log(something);
},"node.js");// 同步調用和異步調用
var c=0;function printIt(){console.log(c);
}// 這里是同步調用
function plus(){c++;
}
plus();
printIt(); //這樣調用printIt()是同步執行的,如果下面有代碼必然會將這個函數執行完后才會繼續執行// 這里是異步調用
function plus(callback){setTimeout(function(){ //定時器是JS里基本的異步函數c++;callback();},1000);
}
plus(printIt); //這樣調用printIt就是異步的了,調用了plus()后下面的代碼就會接著執行
轉載于:https://www.cnblogs.com/3body/p/5417108.html
總結