setTimeout can be declared as below
let
timeoutId = window.setTimeout(myfunction,milliseconds);
or it can simply be declared as
below also since it is in global scope hence the window keyword can be removed.
i.e.
let
timeoutId = setTimeout(myfunction,milliseconds);
We can use this timeoutId to cancel the function before it runs.
➤ Passing an anonymous function to setTimeout function:
We can use this timeoutId to cancel the function before it runs.
➤ Passing an anonymous function to setTimeout function:
setTimeout( ()=> {console.log(“say
hello”); }, 5000);
➤Passing a function expression to the setTimeout function like this:
➤Passing a function expression to the setTimeout function like this:
let myfunc = ()=> { console.log(“say
hello”); };
setTimeout(myfunc, 5000);
➤How to cancel the setTimeout function before
it runs.
<script type="text/javascript">
let tid; // note that tid is undefined and is in global scope here.
$("btnSetTimeOut").click( () => {
tid = setTimeout( () => {
console.log("say hello"); }, 5000);
});
$("btnCancelTimeOut").click(() => { clearTimeout(tid);});
</script>
➤
If we have
Console.log(1);
Console.log(2);
Console.log(3);
Console.log(4);
Console.log(5);
Then all these
statements will execute at once printing 1,2,3,4,5.
But if we want to
print ‘2’ in the last and also we do not want any delay but simply want it
print at the end, then simply wrap it in a setTimeout function for eg.
Console.log(1);
setTimeout( ()=> {
Console.log(2); }, 0);
Console.log(3);
Console.log(4);
Console.log(5);
// Also, note that
here we have given timeout period as zero, but it doesn’t mean that it will
execute immediately. It will only execute in the last only i.e. only when the
EventStack is empty.
This shows the
asynchronous behavior of setTimeout.
In Javascript, we
have an EventStack which basically takes execution by execution and executes it
. So every earlier statement will execute normally, but when the statement with
setTimeout function comes, then it has a special place to go which is called EventTable.
So, the second
statement will go into EventTable and wait for its time, and when that time is over
it will go into EventQueue. Since here we have given zero timeout, it will first
go into EventTable and then immediately go into the EventQueue.
Now, things on the
EventQueue has lower priority then things on the EventStack, Hence the
statement with setTimeout will execute only in the end i.e. only after the
entire EventStack is completely empty.
This makes javascript
non blocking because anything that is asynchronous will come through the
EventQueue.
0 comments:
Post a Comment