I understand how to use setTimeout
function, but I can't find a way to create a function like it.
I have an example:
setTimeout(() => {
console.log('3s');
}, 3000);
while(1);
The result is setTimeout
callback never call so I think it use the same thread like every js other functions. But when it's check the time reach or not? and how it can do that?
Updated
To avoid misunderstanding I update my question.
I can't find a way to create a async function with callback after specify time (without using setTimeout
and don't block entire thread). This function setTimeout
seen like a miracle to me. I want to understand how it work.
Just for the game since I really don't see why you couldn't use setTimeout...
To create a non-blocking timer, without using the setTimeout/setInterval methods, you have only two ways:
Event based timer
One naive implementation would be to use the MessageEvent interface and polling until the time has been reached. But that's not really advice-able for long timeouts...
So instead, if available, one might want to use the Web Audio API and the AudioScheduledSourceNode, which makes great use of the high precision Audio Context's own clock:
Infinite loop on a different thread
Yes, using Web Workers we can run infinite loops without killing our web page:
The reason callback of setTimeout() is not being called is, you have
while(1)
in your code which acts as infinite loop. It will keep your javascript stack busy whole time and that is the reason event loop will never push callback function ofsetTimeout()
in stack.If you remove
while(1)
from your code, callback forsetTimeout()
should get invoked.Following is the implementation of custom setTimeout and setInterval, clearTimeout and clearInterval. I created them to use in sandbox environments where builtin setTimeout and setInterval doesn't work.
Hi you can try this. ] HOpe it will help. Thanks
To create your own setTimeout function, you can use the following function,
setMyTimeout()
to do that without using setTimeout.