UNPKG

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