这是我第一次真正接触JavaScript。当然我以前用过,但是我从未真正写过任何东西。
无论如何,我遇到了一个非常奇怪的问题,希望有人可以帮我解决。
我正在尝试使div的文本从黑变白。很简单,是吗?
以下代码工作。它将颜色更改为白色,但是setTimeout时间500ms被忽略。
[如果您使用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()
上的括号。
括号立即调用该函数。
仅使用此代替:doFade
setTimeout(doFade(), 500);
此行说:“执行doFade()
,然后将返回的任何值传递给setTimeout
,它将在500毫秒后执行此返回值。”也就是说,您正在现场立即拨打doFade()
。
将括号跳过至[[传递函数至setTimeout
:
setTimeout(doFade, 500);
setTimeout(doFade, 500);
或setTimeout("doFade()", 500);