javascript - HTML5 WebWorkers, timed function -


i trying webworker count 100 , update div value of i, div updates straight 100 , seems ignore interval....

javascript (webworker file):

 self.addeventlistener('message', function (e) {          switch (e.data) {              case 'hi worker':                 postmessage('hi boss');                 break              case 'count 100':                 var i;                 (i = 0; < 100; i++) {                     setinterval(postmessage(i + 1), 1000);                 }                  break;             default:                 self.postmessage("not sure how that");         }      }, false); 

main file:

           <script>             var worker = new worker('worker.js');              worker.addeventlistener('message', function (e) {                 console.log("worker said: " + "'" + e.data + "'");                 document.getelementbyid("workercomms").textcontent = "worker said: " + e.data;             }, false);                 </script>     </head>     <body>          <button onclick="worker.postmessage('hi worker');return false;">say 'hi worker'</button>             <button onclick="worker.postmessage('count 100');return false;">count 100</button>              <div id="workercomms">things workers say...</div> 

setinterval(postmessage(i + 1), 1000); calls postmessage(i + 1) , passes return value setinterval, way foo(bar()) calls bar , passes return value foo.

instead:

  1. you want pass function reference setinterval

  2. you want use settimeout, not setinterval

  3. you want vary timeout, because otherwise they'll happen stacked on top of each other 1 second later

something like:

for (i = 1; <= 100; i++) {     settimeout(postmessage.bind(window, i), 1000 * i); } 

would it. schedules 100 timers, @ one-second intervals. uses postmessage.bind(window, i) create function that, when called, postmessage this set window , passing in i first argument. did i 1 100 rather 0 99 avoid having add 1 in both places used it.

alternately, ditch for loop entirely , use setinterval or chained series of settimeout. here's setinterval:

var = 0; var timer = setinterval(function() {     postmessage(++i);     if (i >= 100) {         clearinterval(timer);     } }, 1000); 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -