Why setTimeout does not work as expected? - javascript

Please See the code below.
SetTimeout should execute the seconf function after 100ms time. but first one has blocked second which is unexpected. Settimeout workd in Asynchronous way.
function funcOne(){
console.log("FuncOne invoked")
let i=0;
while(i<10000000000){i++}
console.log("Hello world")
}
function funcTwo(){
console.log("FuncTwo invoked");
}
setTimeout(funcOne,0)
setTimeout(funcTwo,100)
Output should be
FuncOne invoked
FuncTwo invoked
Hello World
But the Actual Output is
FuncOne invoked
HelloWorld
FuncTwo invoked.

Javascript cannot run in separate threads*, so all your code is running in one thread. Anything that is "asynchronous" is just various pieces of code taking turns to run. The Javascript engine will never interrupt one function because another is scheduled to run at a given moment, this is something you need to take care of yourself.
So in your case, funcOne is executed (completely), even though that takes more than 100 ms, then the timeouts are checked and since funcTwo is due to run, it then gets executed (completely).
*well, kind of maybe with workers, but it's not pretty.

The second setTimeout wont be called until your while loop finishes
So you got this order
First timeout called
FuncOne invoked
While loop finishes
Hello World
Second timeout called, after 100ms funcTwo invoked

Related

Does Javascript setInterval function stops if another function is executing same time [duplicate]

setTimeout(function(){
console.log("m");
}, 0);
console.log("s");
Why does this code print "s" before "m", even if the setTimeout callback is supposed to wait for 0 ms?
A browser or node.js always run a single threaded event loop to run your code. On the first run it will always run your synchronous code but may also que up asynchronous events that will call back later. Thats why we call the function here callback function it will be called later.
setTimeout is a microtask.
That means the function that you see isnt gona executed immedantly, it is gonna first queued up and will be executed within the next event loop.
Also a sidefact: 0 ms just means it will minimum wait 0 ms not exact 0
When you create a promise, or call an async function, or set a timeout for 0 milliseconds, the function is immediately queued into the Javascript event loop. Essentially, the function is added to a queue of functions to call, and once the javascript interpreter has nothing to do it'll start calling those functions. So, when you set a timeout for 0 milliseconds, it queues the console.log("m"), then calls the console.log("s"), then it has nothing to do so it finishes the queued console.log("m"), which is why it's out of order.
it just because JS is single-threaded and event loop works that way.
setTimeout has written in a way that it will send you function or whatever you want to do in a callback queue.
and then move forward to the next line, once next line executed it will not run your setTimeout part, or in other words, it will not process the setTimeout part until the stack is not empty.
so this is your code, and it will execute like this.
setTimeout(function () {
console.log("m");
} , 0)
console.log('s');
the first line will execute and it will send the inner part of setTimeout to callback queue and move to the 2nd line.
while 2nd line is executing the setTimeout part will wait till the stack is not emplty and as soon as 2nd line finishes execution,
the setTimeout part will execute,
maybe it's confusing by words, let's see this in action. I bet you can not get a better example than this to understand it, it's explained in the best way by Philip robert.
because JS code goes in order one by one. When you specifying setTimeout to 0 is still waiting, in C++ lang this would be something like this 0.000000245ms, and JS runs often on C++/C browser.
try this simple example
for (let x = 0; x < 500; x++) {
setTimeout(() => console.log(x), 0);
}
console.log('hello');

Why are callbacks of some functions put in Event queue?

I am new to Javascript and Asynchronous programming, a few things confuse me.
Consider the following code
function fun(callback) {
console.log('a');
setTimeout(callback,0);
console.log('c');
}
fun(() => {console.log('b');});
I know that the callback of setTimeout function is put inside Event queue and rest are put inside call stack, tasks in event queue are executed only when call stack is empty, but I know that is not the case for all callbacks.
What makes functions like setTimeout special ?
If there are any misfacts in my understandings please point it out.
You know almost all, If we use setTimeout example like this : setTimeout(func, 0), This ensures that the func is scheduled as soon as possible. But the timer does this only when the current code operation is finished. Therefore, the timer starts running "right after" the current job. In other words, "asynchronous". For example, the code below prints "Hello" followed by "World".
setTimeout(() => alert("World"), 0);
alert("Hello");
In the first line it means "queue the call after 0ms".But the timer looks after "check queue first" ie after running the current code.From this "Hello" is written before "World" after.I hope I could explain. Happy coding!!!

Sequence of execution for JavaScript setTimeout

I am trying to understand the way setTimeout gets executed.
In the sample below, I was expecting to see 'Inside setTimeout' as the second line in the console log.
But, I always see 'Inside setTimeout' as the third line in the console log.
This is what I see in the log consistently:
First
Last
Inside setTimeout
Any idea why is it behaving this way?
<script>
console.log('First');
// NOTE: 0 milliseconds.
setTimeout(function() {console.log('Inside setTimeout')}, 0);
console.log('Last');
</script>
Even with a 0ms timeout, it still schedules the function to be called asynchronously. The way setTimeout works is:
Do some validations on the input
Add the function to a list to be called as of X time
Return
Later, when the specified amount of time has passed, the browser will queue a task to call the function, which will be processed by the event loop when the tasks in front of it have been processed.
It never calls the function immediately. That would chaotic; by always calling it asynchronously, it's consistent. (That's also why a promise's then and catch handlers are always called asynchronously, even if the promise is already settled.)
All of the gory details are in the specification.
Working of the setTimeout(function, delayTime) with an example:
More details can be found here.
function main(){
console.log('A');
setTimeout(
function display(){ console.log('B'); }, 0);
console.log('C');
}
main();
// Output
// A
// C
// B
The call to the main function is first pushed into the stack (as a frame). Then the browser pushes the first statement in the main function into the stack which is console.log(ā€˜Aā€™). This statement is executed and upon completion that frame is popped out. Alphabet A is displayed in the console.
The next statement (setTimeout() with callback exec() and 0ms wait time) is pushed into the call stack and execution starts. setTimeout function uses a Browser API to delay a callback to the provided function. The frame (with setTimeout) is then popped out once the handover to browser is complete (for the timer).
console.log(ā€˜Cā€™) is pushed to the stack while the timer runs in the browser for the callback to the exec() function. In this particular case, as the delay provided was 0ms, the callback will be added to the message queue as soon as the browser receives it (ideally).
After the execution of the last statement in the main function, the main() frame is popped out of the call stack, thereby making it empty. For the browser to push any message from the queue to the call stack, the call stack has to be empty first. That is why even though the delay provided in the setTimeout() was 0 seconds, the callback to exec() has to wait till the execution of all the frames in the call stack is complete.
Now the callback exec() is pushed into the call stack and executed. The alphabet C is display on the console. This is the event loop of javascript.
so the delay parameter in setTimeout(function, delayTime) does not stand for the precise time delay after which the function is executed. It stands for the minimum wait time after which at some point in time the function will be executed.
--Copied from medium
PS: The best working video example by Philip Roberts.

Javascript - how event listeners work under the hood

I have the following code:
function sayHiLater(){
var greeting = "Hi!";
setTimeout(function() {
console.log(greeting);
}, 3000);
console.log("Hello before hi");
}
sayHiLater();
I would like to better understand how event listeners work under the hood,
so in my example above, as setTimeOut is being executed, what really happens?
I know it creates a new execution context, but my question is; does that execution context is simply being delayed for 3 seconds, meaning the execution stack is moving on to other things in the meanwhile, and as the 3 seconds are over it comes back to that execution context, or is it simply passing to the browser engine some sort of a reference of the anonymous function argument, telling it when to fire, and then right away the setTimeOut execution context is being popped off the execution stack. Or am I just completely far off from what's really happening. Thank you for your time.
Is it simply passing to the browser engine some sort of a reference of the anonymous function argument, telling it when to fire, and then right away the setTimeOut execution context is being popped off the execution stack.
Yes, that's exactly what is happening. The setTimeout execution context immediately returns (and jumps to the next statement, your console.log).
Then after your current turn completes and no more code is to execute, the engine goes back to the event loop and waits for something to happen. After 3 seconds, the time is ready to fire the callback, and when no other code is already executing the event loop starts the anonymous function.
So setTimeout does not really call its callback, it only schedules it for later. It will be called by the event loop itself when the timer has run out.
Notice that the anonymous function that is put on the timer is a closure (it closes over the greeting variable), so the variable environment ("scope") of sayHiLater will be retained (not garbage-collected) even after the sayHiLater execution context is popped off the stack, until the callback is going to be executed.

Functions don't execute in the order I expect when using setTimeout()

I have this code where I am using two javascript functions that do some manipulating for me. One function does some calculation but calls the other function before doing anything else. When the other function returns to it, it is supposed to do the final calculations.
The problem: The call to the other function is not executing properly. Even before the second function returns the first function executes completely.
code:
firstfunction{
secondfunction();
do something more nothing related to second
}
secondfunction(){
setTimeout(func1(){
do something independently
then call func1 depending on some condition
},time);
}
second function is used somewhere else also and is working fine.
My question:
I used this code thinking that the first function will not execute before second function executes completely. Is it right? Isn't this the way javascript functions should run? The first function executes completely before second returns. I am sure of this because after second returns the position for the graphic first is supposed to place that graphic on screen. But the first executes completely and the graphic is placed awkwardly on screen and viewer can see it moving to right position given by the loop of second. Is setTimeout causing this problem?
Please help.
This happens because you use setTimeout. setTimeout will make it asynchronous. Execution of second function will be completed after setting the interval and execution-flow will go back to first function. So you have to split your first function and make a third function which will have the final steps. This third function has to be invoked from the setTimeout handler.
function firstfunction(){
secondfunction(params);
}
function secondfunction(params){
setTimeout(func1(){
do something independently
then call thirdfunction depending on some condition
},time);
}
function thirdfunction(params){
do something more nothing related to second
}
In this method you have to pass everything as parameters from one function to other.
You can also do this in a different way by making third one a callback function. This way you can make everything in the scope of firstfunction available for thirdfunction.
function firstfunction{
secondfunction(thirdfunction);
function thirdfunction(){
do something more nothing related to second
}
}
function secondfunction(callback){
setTimeout(func1(){
do something independently
then call callback depending on some condition
},time);
}
"Even before the second function returns the first function executes completely."
No, in fact the second function returns immediately after it calls setTimeout() - it does not wait for the timeout to occur. The func1() function that you pass to setTimeout() will be called later after the specified timeout delay, but meanwhile execution continues with whatever follows the setTimeout() call (in this case the end of the function follows, so it returns to the first function and then the rest of the first function continues). To put it another way, setTimeout() does not pause execution.
If you need something to happen after the timeout you need to either place it in the function you pass to setTimeout() or call it from that function.

Categories

Resources