JavaScript setTimeout() won't wait to Execute?

♀尐吖头ヾ 提交于 2019-11-26 03:27:07

问题


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


回答1:


alertBox()

Doesn't this look like an immediate function call?

Try passing the function (without executing it) instead:

setInterval(alertBox, 5000);



回答2:


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

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


来源:https://stackoverflow.com/questions/11837562/javascript-settimeout-wont-wait-to-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!