What is the purpose of Web Workers in HTML5?
A
To create web pages B
To access device hardware C
To run JavaScript in the background D
To store data in the browser
Analysis & Theory
Web Workers run JavaScript in the background without blocking the main UI thread.
Which constructor is used to create a new Web Worker?
A
new WorkerThread('worker.js') B
createWorker('worker.js') C
new WebWorker('worker.js') D
new Worker('worker.js')
Analysis & Theory
`new Worker('worker.js')` creates a new Web Worker.
How does the main script communicate with a Web Worker?
A
Using `postMessage()` and `onmessage` B
Using `send()` and `receive()` C
Using `emit()` and `listen()` D
Using `dispatch()` and `trigger()`
Analysis & Theory
Communication between the main script and the Web Worker is done using `postMessage()` and the `onmessage` event.
Which method terminates a Web Worker from the main script?
A
worker.stop() B
worker.kill() C
worker.terminate() D
worker.shutdown()
Analysis & Theory
`worker.terminate()` stops the Web Worker immediately.
What happens if a Web Worker tries to access the DOM?
A
It updates the DOM directly B
It throws an error C
It sends a message to update the DOM D
Nothing happens
Analysis & Theory
Web Workers cannot access the DOM directly; doing so will throw an error.
Which file type should be used to define a Web Worker script?
A
.xml B
.html C
.js D
.json
Analysis & Theory
Web Worker code must be placed in a separate JavaScript file (`.js`).
How do you listen for messages from a Web Worker in the main thread?
A
worker.onmessage = function(e) { ... } B
worker.listen = function(e) { ... } C
onWorkerMessage = function(e) { ... } D
worker.message = function(e) { ... }
Analysis & Theory
`worker.onmessage` is used to handle messages sent from the Web Worker.
Can Web Workers use `setTimeout()` and `setInterval()`?
A
No B
Only `setTimeout()` C
Yes, both are supported D
Only `setInterval()`
Analysis & Theory
Web Workers can use both `setTimeout()` and `setInterval()`.
Which method sends a message to a Web Worker?
A
worker.send() B
worker.emit() C
worker.dispatch() D
worker.postMessage()
Analysis & Theory
`worker.postMessage()` sends a message to the Web Worker.
What happens to a Web Worker when the page is closed?
A
It continues running in the background B
It pauses until the page reloads C
It is automatically terminated D
It saves state and sleeps
Analysis & Theory
Web Workers are terminated automatically when the page that created them is closed.