有一段html的小代碼,如下:function init(){ var planet=document.getElementById("greenplanet");
planet.innerHTML="RED ALERT: hit by phaser fire!"
setTimeout(planet.setAttribute("class","bluetext"),1000);
setTimeout(planet.setAttribute("class","redtext"),2000);然而,這樣執(zhí)行時,會直接將Attribute變成redtext,沒有倒計時1000ms(我試過用5000ms,確實沒有倒計時),bluetext這一句也沒有執(zhí)行。我試著將代碼改成:function init2(){ var planet=document.getElementById("greenplanet");
planet.innerHTML="RED ALERT: hit by phaser fire!"; function a(){
planet.setAttribute("class","bluetext");
} function b(){
planet.setAttribute("class","redtext");
}
setTimeout(a,1000);
setTimeout(b,2000);
}就可以了。兩個setAttribute分別在倒計時后觸發(fā)。前后兩段代碼的區(qū)別,就是后一段將setAttribute代碼直接封裝到一個函數內。可是setTimeOut的第一個參數,不是既可以是函數,也可以是代碼段碼?
JavaScript SetTimeout輸入參數的問題
胡說叔叔
2018-09-14 14:09:25