Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 436
MasonWinsauer Avatar asked Aug 06 '12 23:08

MasonWinsauer


People also ask

Why does setTimeout run immediately?

Actually setTimeOut() function is an asynchronous function and when you pass a function as one of the parameter to the setTimeOut() function, your script actually does not want to waste your time and wants to execute your passed function as soon as possible.

How do you wait for setTimeout to finish?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.

Does setTimeout pause execution?

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

Why is setTimeout not working?

This is due to when a function is executed as a parameter to setTimeout , the execution context is different to the execution context of the function! Now this will print out undefined because the this keyword is executed in the context of the setTimeout function and is therefore not defined.


1 Answers

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

function myFunction(){
    setTimeout(doSomething, 3000); // no () on the function
};
like image 69
hvgotcodes Avatar answered Nov 05 '22 08:11

hvgotcodes