gpt4 book ai didi

javascript - setTimeout 忽略超时? (立即开火)

转载 作者:IT王子 更新时间:2023-10-29 03:19:47 26 4
gpt4 key购买 nike

这是我第一次真正深入了解 JavaScript。当然我以前用过它,但我从来没有真正从头开始写过任何东西。

无论如何,我遇到了一个非常奇怪的问题,我希望有人能为我解决。

我正在尝试使 div 中的文本从黑色淡化为白色。很简单,是吗?

以下代码有效。它将颜色更改为白色,但是,500 毫秒的 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);
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com