JavaScript setTimeout() won't wait to Execute?

MasonWinsauer picture MasonWinsauer · Aug 7, 2012 · Viewed 9k times · Source

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 is it that causes this to execute IMMEDIATELY, rather than waiting the 3 seconds set, as well as only executing the alert ONCE, rather than at the scheduled 5 second intervals?

Thanks for any help you can provide!

Mason

Answer

Ates Goral picture Ates Goral · Aug 7, 2012
alertBox()

Doesn't this look like an immediate function call?

Try passing the function (without executing it) instead:

setInterval(alertBox, 5000);