11

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

MasonWinsauer
  • 673
  • 3
  • 14
  • 32

3 Answers3

21
alertBox()

Doesn't this look like an immediate function call?

Try passing the function (without executing it) instead:

setInterval(alertBox, 5000);
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
14

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

function myFunction(){
    setTimeout(doSomething, 3000); // no () on the function
};
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

Following codes executing differently,

setTimeout(console.log('Nuwan'),0)---(A); and 
setTimeout(function(){console.log('Nuwan'),0}) --- (B)

The reason is when (B) is executing, CallStack in javascript runtime push the setTimeout() to web API and WebAPI waits 0 seconds to push the callback function to the event queue and then EventLoop pushes the callback to the stack after the current stack is empty.

In Case (A), console.log() directly calling because it is in the WepAPI, no need to go for an event loop to execute.

More Ref: WebAPIs: https://developer.mozilla.org/en-US/docs/Web/API/Console_API Javascript Runtime and Event Loop: https://cybrohosting.com/knowledgebase/17/How-JavaScript-works-in-browser-and-node.html

Nuwa
  • 461
  • 4
  • 10