问题
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