简体   繁体   中英

Executing a function after a period of time in Javascript

I am trying to write a user script that will hide certain elements from a page. The problem is the elements do not appear until a few seconds after the page has loaded, so I am trying to do it with a few seconds of delay.

This is the code I have:

function hide_stuff()
{
    var e = document.getElementsByClassName("tab");
    if(e) 
        alert("got elements");
    else 
        alert("didn't get elements");
    for( var i = 0; i < e.length; i++){
        if (!e[i].id)
            e[i].style.display = "hidden";
    }
}

setTimeout(hide_stuff(), 5000);

The problem is it doesn't delay at all. The "got elements" alert (which I added as a debugging aid), fires immediately when the page loads. I can't see what I'm doing wrong, although I'm sure it's probably something obvious.

Any help?

Change

setTimeout(hide_stuff(), 5000);

to

setTimeout(hide_stuff, 5000);

Instead of passing the function, you were calling it immediately (and passing undefined to setTimeout ).

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