JavaScript setTimeout() won't wait to Execute? [duplicate]
Asked Answered
F

3

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

Fuchsin answered 6/8, 2012 at 23:59 Comment(6)
Well, the callback is invoked immediately (and the result is passed to setTimeout) .. pass the Function-object instead.Slivovitz
This is probably the single most asked javascript question on SO.Craze
@Craze I think closured variables in loops might tie it .. ;-)Slivovitz
Well I certainly feel like a fool - This is what I get for leaving JS alone for so long >.<Fuchsin
@Fuchsin Feel your pain.Rolling
Refer to my comment, it might useful for you.https://mcmap.net/q/959256/-javascript-settimeout-won-39-t-wait-to-execute-duplicateNielsen
J
21
alertBox()

Doesn't this look like an immediate function call?

Try passing the function (without executing it) instead:

setInterval(alertBox, 5000);
Jonasjonathan answered 7/8, 2012 at 0:0 Comment(0)
T
14

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

function myFunction(){
    setTimeout(doSomething, 3000); // no () on the function
};
Tempera answered 7/8, 2012 at 0:0 Comment(0)
N
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

Nielsen answered 11/3, 2020 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.