InterviewSolution
| 1. |
What are Web workers? |
|
Answer» The HTML5 Web WORKER was made to make the web asynchronous. We all know that JavaScript is single THREADED. It will stop the execution of the web-browser, till a script is COMPLETED and will not proceed further. Sometimes, it is not desirable. We want to show our visitor the website and let the heavy script which might be fetching big data from an API run in the background and complete. In these situations, web workers come to the rescue. Web workers are initialized using var worker = new Worker(‘extremeLoop.js'); Here, extremeLoop.js is our computationally heavy JavaScript file which we want to run separately. Once the Web Worker is started, communication between a web worker and its PARENT is generally done using the postMessage() method. Then the message is passed by Web Worker to the main page using onmessage event. Here in the example, we have a simple web worker to CALCULATE the prime. <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Web Worker example</title> </head> <body> <p>The highest prime number discovered so far is: <output id="result"></output></p> <script> var worker = new Worker('extremeLoop.js'); worker.onmessage = function (event) { document.getElementById('result').textContent = event.data; }; </script> </body> </html>Save the JavaScript file in the same directory as extremeLoop.js var n = 1; search: while (true) { n += 1; for (var i = 2; i <= Math.sqrt(n); i += 1) if (n % i == 0) continue search; postMessage(n); }Now, open the browser and you will get. |
|