html - Javascript with multithreading? -
i coming desktop application background, when learning javascript, difficult understand threading mechanism in javascript.
for example:
<!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ (var = 0 ; < 100000 ; ++){ $("#loop1").html(i); } }); $("#btn2").click(function(){ (var = 0 ; < 100000 ; ++){ $("#loop2").html(i); } }); }); </script> </head> <body> loop 1 : <p id="loop1"></p> <button id="btn1">button 1</button> <br/><br/><br/> loop 2 : <p id="loop2"></p> <button id="btn2">button 2</button> </body> </html>
when click on button 1, browser hang, button 2 not responsive when click it. in desktop application, post looping background thread. how going in javascript? or best way in handling long processing in javascript?
edited :
the code below not work, not sure why.
$("#btn1").click(function(){ settimeout( function(){ (var = 0 ; < 100000 ; ++){ $("#loop1").html(i); } } , 0); });
as previous answers stated, webworkers javascript's option multi-threading. unfortunately, there's no hope if want dom modifications.
what people forget when call functions settimeout
, setinterval
the ui not freeze , still receives updates.
function btnclickhandler() { settimeout(dostuff, 1); // prevent ui freeze } function dostuff() { // stuff here }
in case:
var i, interval; $("#btn1").click(function(){ = 0; // reset // create interval interval = setinterval(btn1handler, 1); // run btn1handler every 1ms }); function btn1handler() { $("#loop1").html(i); if(i++ >= 100000) { // cancel interval clearinterval(interval); } }
Comments
Post a Comment