JavaScript setTimeout() won't wait to Execute?

2019-01-04 14:36发布

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

2条回答
仙女界的扛把子
2楼-- · 2019-01-04 15:20
alertBox()

Doesn't this look like an immediate function call?

Try passing the function (without executing it) instead:

setInterval(alertBox, 5000);
查看更多
闹够了就滚
3楼-- · 2019-01-04 15:27

its because you are executing the function, not passing a function object.

function myFunction(){
    setTimeout(doSomething, 3000); // no () on the function
};
查看更多
登录 后发表回答