有一段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);
然而,这样执行时,会直接将Attribute变成redtext,没有倒计时1000ms(我试过用5000ms,确实没有倒计时),bluetext这一句也没有执行。
我试着将代码改成:
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分别在倒计时后触发。前后两段代码的区别,就是后一段将setAttribute代码直接封装到一个函数内。可是setTimeOut的第一个参数,不是既可以是函数,也可以是代码段码?
根据标准,你确实可以传入一个回调函数(
function
)或一个代码片段(code
)作为第一个参数,但是如果是code
,你需要用引号包裹起来。另外,建议不要传入
code
型的参数,理由和eval
一样。参考: window.setTimeout | MDN