javascript - Why does the following JS function wreck the browser process? -


var wait = function (milliseconds) {     var returncondition = false;     window.settimeout(function () { returncondition = true; }, milliseconds);     while (!returncondition) {}; }; 

i know there have been many posts why not try implement wait() or sleep() function in javascript. not making usable implementation purposes, rather making work proof of concept's sake.

trying

console.log("starting...");wait(3000);console.log("...done!"); 

freezes browser. why wait() seemingly never end?

edit: answers far, wasn't aware of while loop never allowing other code execute.

so work, then?

var wait = function (milliseconds) {     var returncondition = false;     var setmytimeout = true;     while (!returncondition) {         if (setmytimeout) {             window.settimeout(function() { returncondition = true; }, milliseconds);             setmytimeout = false;         }     };     return; }; 

javascript executed in single thread. when execution path exits can execution path begin. thus, when launch wait(3000), following happens:

  • returncondition set false
  • a timeout scheduled
  • an infinite loop started.

each <script> tag, each event being handled, , each timeout (and ui refresh, in case of browser) initiate separate execution path. thus, timeout of 3000 not guaranteed run in 3000ms, @ time after 3000ms when engine "free".

the wait function never exits, script's execution path never ends, , scheduled timeout's turn never comes.

edit:

that means, once <script> tag has begun, or node.js has started executing javascript file, execution has reach bottom before else can happen. if function started result of event or timeout, function needs exit before else can happen.

<script>   console.log("script top");   function thetimeout() {     console.log("timeout top");     // long     console.log("timeout bottom");   }   settimeout(thetimeout, 0);   settimeout(thetimeout, 0);   console.log("script bottom"); </script> 

there 3 execution paths here. first <script> tag's: starts printing "script top", schedules 2 timeouts (for "right now"), prints "script bottom", , end of <script> reached , interpreter idle. means has time execute execution path, , there 2 timeouts waiting, selects 1 of them , starts executing it. while executing, again nothing else can execute (even ui updates); other timeout, though scheduled @ "immediately", left wait till first timeout's execution path ends. when does, second timeout's turn comes, , gets executed well.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -