WEB WORKERS
The Web Workers paradigm allows to write multi-threading code in JavaScript.
Remark: since the Web Workers code is placed in some external files (i.e. not this page) they can not access the
window
, document
and parent
JavaScript objects.
For a simple introduction about Web Workers see
W3C Schools.
A more complete tutorial is available on
HTML5 Rocks.
For a discussion about the security issues of the postMessage()
function see Mozilla reference
site.
To browse the code click on the Show Code, Show Markup and Show Web Worker labels below.
var n = 0 ; // Function invoked by the "08-web-workers.php" page. // This function relies on the new cross-domain command: "postMessage(message, targetOrigin)" // If no target is specified, the message is send to the current page. // See: https://developer.mozilla.org/en-US/docs/DOM/window.postMessage function timedCount() { n = n + 1 ; postMessage(n) ; setTimeout("timedCount()", 1000) ; } // Starting thread timedCount() ;
// Echoing messages sent by the parent page (i.e. "08-web-workers.php") // See: http://www.html5rocks.com/en/tutorials/workers/basics/ var n = 0 ; // Just a courtesy alert (used below) var msg = "Remark: since the worker reference in the caller page (the 'second' JS variable) has not been re-initialized, "; msg += "when this worker is automatically closed it's NOT possibile to re-execute it!"; // Listener for messages sent by the "08-web-workers.php" page using the "second.postMessage" command. // Here we receive such message and we echo it to the caller, using the "self.postMessage" instruction. self.addEventListener('message', function(e) { setInterval(function() { n++ ; self.postMessage("Echo (" + n + ") : " + e.data) ; // Terminate this worker within this file (after 4 interations) if (n >= 4) { self.postMessage("Automatically closing worker -> " + self) ; self.postMessage(msg) ; self.close() ; } }, 1000) ; // End of setInterval }, false) ; // End of addEventListener