HTML5 HTML5 Web Workers 1 — Questions and Answers
Question 1: What is the primary purpose of HTML5 Web Workers?
- To run JavaScript in a background thread without blocking the main UI thread (Correct answer)
- To load external CSS stylesheets asynchronously
- To create animated graphics on a canvas element
- To store large amounts of data in the browser cache
Correct answer: To run JavaScript in a background thread without blocking the main UI thread
Web Workers allow scripts to run in background threads, keeping the main thread free and preventing UI freezing during heavy computations.
Question 2: Which of the following correctly creates a new Web Worker?
- var worker = new Worker('worker.js'); (Correct answer)
- var worker = Worker.create('worker.js');
- var worker = new Thread('worker.js');
- var worker = document.createWorker('worker.js');
Correct answer: var worker = new Worker('worker.js');
The Worker constructor takes the URL of a script file as its argument to instantiate a new background worker.
Question 3: How does the main thread send a message to a Web Worker?
- worker.postMessage(data) (Correct answer)
- worker.sendMessage(data)
- worker.emit('message', data)
- worker.dispatch(data)
Correct answer: worker.postMessage(data)
The postMessage() method is used on both sides of the worker communication channel to pass data.
Question 4: Inside a Web Worker, which global object is available instead of 'window'?
- self (Correct answer)
- global
- worker
- context
Correct answer: self
Inside a Web Worker, 'self' refers to the worker's global scope (DedicatedWorkerGlobalScope), since 'window' is not available.
Question 5: Which of the following resources is NOT accessible inside a Web Worker?
- The DOM (document object) (Correct answer)
- The XMLHttpRequest object
- The navigator object
- The setTimeout function
Correct answer: The DOM (document object)
Web Workers run in a separate thread and do not have access to the DOM, window, or document objects for thread-safety reasons.
Question 6: How do you terminate a Web Worker from the main thread?
- worker.terminate() (Correct answer)
- worker.stop()
- worker.kill()
- worker.close()
Correct answer: worker.terminate()
The terminate() method is called on the worker instance from the main thread to immediately stop the worker.
Question 7: Which event listener is used in the main thread to receive messages from a Web Worker?
- worker.onmessage (Correct answer)
- worker.onreceive
- worker.onresponse
- worker.ondata
Correct answer: worker.onmessage
The 'onmessage' event handler fires in the main thread whenever the worker calls postMessage(), with the data accessible via event.data.
What is the primary purpose of HTML5 Web Workers?