简体   繁体   中英

Javascript - Why isn't this setTimeout function working?

For the life of me I cannot seem to get any kind of results from this snippet. I want the function to add and then remove an additional class to all elements with the id of "ring" with an added delay after each execution. Other examples of the setTimeout() function have it written like this.

function flash_rings()
{
    var e = document.getElementById("ring");
    setTimeout(function(){e.className = "ring hover";}, 1000);
    setTimeout(function(){e.className = "ring";}, 1000);
}

The class has been written and tested, so I know it's not fault of the CSS. The function is due to be called in the <body> 's onload= event. The snippet of code is located at the very bottom of the page, immediately above the </body> tag.

Help?

Thanks,

~Zion

As Pablo said , they happen one right after another, one second later.

If you want the second to happen a second after the first:

function flash_rings()
{
    var e = document.getElementById("ring");
    setTimeout(function(){
        e.className = "ring hover";
        setTimeout(function(){
            e.className = "ring";
        }, 1000);
    }, 1000);
}

Or

function flash_rings()
{
    var e = document.getElementById("ring");
    setTimeout(function(){ e.className = "ring hover"; }, 1000);
    setTimeout(function(){ e.className = "ring"; }, 2000);
}

That latter one is a bit less connected, but you can be fairly sure the second one will happen roughly a second after the first, barring the page being really busy doing other things. (You wouldn't do that if the first weren't also a timer thing; if it were ajax or something, you'd definitely wait for the first to complete before scheduling the second.)

They both fire off almost in the same instance. One Timeout will not be waiting for another. Just change that second to 2000:

setTimeout(function(){e.className = "ring";}, 2000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM