setTimeout忽略超时? (立即开火) [英] setTimeout ignores timeout? (Fires immediately)

查看:117
本文介绍了setTimeout忽略超时? (立即开火)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my first real dive into JavaScript. Sure I've used it before, but I've never really written anything from scratch.

无论如何,我有一个非常奇怪的问题,我希望有人能想到对我来说。

Anyway, I'm having a very strange problem that I hope someone can figure out for me.

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

I'm trying to make the text from a div fade from black to white. Simple, yeah?

以下代码有效。它会将颜色更改为白色,但是,500ms的setTimeout时间将被忽略。

The following code works. It will change the color to white, however, the setTimeout time of 500ms is being ignored.

如果您使用Chrome并查看JS控制台,您将很容易看到几乎是瞬间调用doFade()方法,而不是每500毫秒。

If you use Chrome and look at the JS console, you'll easily see that the doFade() method is being called almost instantaneously, not every 500 milliseconds.

任何人都可以解释这个吗?

Can anyone explain this?

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()上的括号。

You need to get rid of the parentheses on doFade().

括号立即调用该函数。

The parentheses invoke the function instantly.

只需使用它: doFade

这篇关于setTimeout忽略超时? (立即开火)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆