回調函就是一個函數調用另一個函數的過程,在編碼過程中我們經常會遇到在上一個函數執行完后,才開始執行下一個函數。
下面是代碼生成一個div然后讓他的左邊距增加到100然后停止。
function fun1(){
var div =document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.background ='red';
document.body.appendChild(div);
var s = 0;
var timer = null;
timer = setInterval(function(){
s ++;
if(s==1000){
clearInterval(timer);
}
div.style.marginLeft = s+'px';
},1);
}
fun1();
上面是我們經常會遇見的情況,當一個動態效果執行完后,我們會想接着再執行另一個事件,就需要把另一個函數當參數傳遞進去,當上一個函數執行完后,執行下一個函數。
代碼如下。
fun1(fun2); function fun1(callback) { var div = document.createElement('div'); div.style.width = '100px'; div.style.height = '100px'; div.style.background = 'red'; document.body.appendChild(div); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(); } div.style.marginLeft = s + 'px'; }, 1); } function fun2() { var div1 = document.createElement('div'); div1.style.width = '100px'; div1.style.height = '100px'; div1.style.background = 'red'; div1.style.marginTop = '100px'; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); } div1.style.marginLeft = s + 'px'; }, 1); }
上面代碼中fun2在fun1執行是被作為一個參數傳進了,fun1里面。當fun1里s等於1000是,定時器停止然后開始執行fun2。
如果當fun2執行完后我們還需要回調,那么把另一個函數傳入fun2就行了;
fun1(fun2); function fun1(callback) { var div = document.createElement('div'); div.style.width = '100px'; div.style.height = '100px'; div.style.background = 'red'; document.body.appendChild(div); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(fun3); //這里的callback()原型就是fun2,把fun3當做參數傳進去,不要用fun3(),這樣就是執行了; } div.style.marginLeft = s + 'px'; }, 1); } function fun2(callback) { var div1 = document.createElement('div'); div1.style.width = '100px'; div1.style.height = '100px'; div1.style.background = 'red'; div1.style.marginTop = '100px'; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); callback(); } div1.style.marginLeft = s + 'px'; }, 1); } function fun3() { var div1 = document.createElement('div'); div1.style.width = '100px'; div1.style.height = '100px'; div1.style.background = 'red'; div1.style.marginTop = '100px'; document.body.appendChild(div1); var s = 0; var timer = null; timer = setInterval(function () { s++; if (s == 1000) { clearInterval(timer); } div1.style.marginLeft = s + 'px'; }, 1) }