webworkers.html (2123B)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>math.js | web workers</title> 6 </head> 7 <body> 8 9 <p> 10 In this example, a math.js parser is running in a separate 11 <a href="https://www.html5rocks.com/en/tutorials/workers/basics/">web worker</a>, 12 preventing the user interface from freezing during heavy calculations. 13 </p> 14 15 <p id="results"></p> 16 17 <script> 18 /** 19 * MathWorker evaluates expressions asynchronously in a web worker. 20 * 21 * Example usage: 22 * 23 * const worker = new MathWorker() 24 * const expr = '12 / (2.3 + 0.7)' 25 * worker.evaluate(expr, function (err, result) { 26 * console.log(err, result) 27 * }) 28 */ 29 function MathWorker () { 30 this.worker = new Worker('worker.js') 31 this.callbacks = {} 32 this.seq = 0 33 34 // create a listener to receive responses from the web worker 35 const me = this 36 this.worker.addEventListener('message', function(event) { 37 const response = JSON.parse(event.data) 38 39 // find the callback corresponding to this response 40 const callback = me.callbacks[response.id] 41 delete me.callbacks[response.id] 42 43 // call the requests callback with the result 44 callback(response.err, response.result) 45 }, false) 46 } 47 48 /** 49 * Evaluate an expression 50 * @param {string} expr 51 * @param {Function} callback Called as callback(err, result) 52 */ 53 MathWorker.prototype.evaluate = function evaluate (expr, callback) { 54 // build a request, 55 // add an id so we can link returned responses to the right callback 56 const id = this.seq++ 57 const request = { 58 id: id, 59 expr: expr 60 } 61 62 // queue the callback, it will be called when the worker returns the result 63 this.callbacks[id] = callback 64 65 // send the request to the worker 66 this.worker.postMessage(JSON.stringify(request)) 67 } 68 69 // create a MathWorker 70 const worker = new MathWorker() 71 72 // evaluate an expression via the worker 73 worker.evaluate('12 / (2.3 + 0.7)', function (err, result) { 74 document.getElementById('results').innerHTML += 'result: ' + result + '<br>' 75 }) 76 77 </script> 78 79 </body> 80 </html>