function alertBox(){ al...">

JavaScript setTimeout () will not wait for execution?

Consider the following example:

<script type="text/javascript">
    function alertBox(){
        alert('Hello World!');
    }
    function doSomething(){
        setInterval(alertBox(), 5000); //This is for generic purposes only
    };
    function myFunction(){
        setTimeout(doSomething(),3000);
    };

    myFunction();
</script>

What does it cause it to execute IMMEDIATELY , and not wait for a 3-second dialing, and also execute only an ONCE warning , and not at the planned 5 second intervals?

Thanks for any help you can provide!

Mason

+5
source share
2 answers
alertBox()

Doesn't this look like an immediate function call?

Try passing a function (without executing it):

setInterval(alertBox, 5000);
+13
source

because you are executing a function, not passing an object to a function.

function myFunction(){
    setTimeout(doSomething, 3000); // no () on the function
};
+11
source

All Articles