Created
March 11, 2012 00:23
-
-
Save icodejs/2014200 to your computer and use it in GitHub Desktop.
Web Workers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Consider, for example, parsing a large JSON string. Suppose that the data is large | |
// enough that parsing takes at least 500 milliseconds. That is clearly too long to allow | |
// JavaScript to run on the client, as it will interfere with the user experience. This particular | |
// task is difficult to break into small chunks with timers, so a worker is the ideal solution. The | |
// following code illustrates usage from a web page: | |
var worker = new Worker("jsonparser.js"); | |
//when the data is available, this event handler is called | |
worker.onmessage = function(event){ | |
//the JSON structure is passed back | |
var jsonData = event.data; | |
//the JSON structure is used | |
evaluateData(jsonData); | |
}; | |
// pass in the large JSON string to parse worker.postMessage(jsonText); | |
// The code for the worker responsible for JSON parsing is as follows: | |
// inside of jsonparser.js | |
// this event handler is called when JSON data is available | |
self.onmessage = function(event){ | |
//the JSON string comes in as event.data | |
var jsonText = event.data; | |
//parse the structure | |
var jsonData = JSON.parse(jsonText); | |
//send back to the results | |
self.postMessage(jsonData); | |
}; | |
// Note that even though JSON.parse() is likely to take 500 milliseconds or more, there is | |
// no need to write any additional code to split up the processing. This execution takes | |
// place on a separate thread, so you can let it run for as long as the parsing takes without | |
// interfering with the user experience. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment