这是我第一次真正深入JavaScript。当然,我以前使用过它,但我从来没有从头开始写任何东西。setTimeout忽略超时? (立即着火)
无论如何,我有一个很奇怪的问题,我希望有人能找到我。
我试图使文本从div淡出从黑色到白色。简单,是吗?
以下代码作品。它会将颜色更改为白色,但是,500ms的setTimeout时间将被忽略。
如果您使用Chrome并查看JS控制台,您将很容易看到doFade()方法几乎是瞬间调用,而不是每500毫秒。
任何人都可以解释这一点吗?
var started = false;
var newColor;
var div;
var hex = 0;
function fadestart(){
if (typeof fadestart.storedColor == 'undefined') {
div = document.getElementById('test');
fadestart.storedColor = div.style.color;
}
if(!started){
console.log('fadestart');
newColor = fadestart.storedColor;
started = true;
setTimeout(doFade(), 500);
}
}
function fadestop(){
console.log('fadestop');
div.style.color = fadestart.storedColor;
started = false;
hex = 0;
}
function doFade(){
if(hex<=238){
console.log(hex);
hex+=17;
div.style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout(doFade(), 500);
}
}
其实,你想 'dofade()' 作为一个字符串,用引号。不过,你有根本原因。 – 2010-11-08 02:03:12
是'func'求值到函数本身,而'func()'调用函数并计算其返回值。 – 2010-11-08 02:03:46
很确定你不需要报价。你应该能够把doFade或“doFade”。我认为,甚至可能会略微提高性能,以便不将字符串“doFade”转换为函数句柄。 – KeatsKelleher 2010-11-08 02:04:48