I dette eksempelet starter vi en worker som teller ned sekunder.
Dette kunne vi selvsagt gjort uten en worker, men eksempelet illustrerer noen mekanismer i
kommunikasjonen mellom worker og "hovedskriptet".
Websiden som drar det hele ser slik ut:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>test2</title>
<script>
try{
var worker = new Worker('test2Work.js');
worker.onmessage = function (event) {
setMessage(event.data);
};
worker.onerror = function (event) {
console.log(event.message, event);
};
// start counting down from 10
worker.postMessage("10");
}
catch(e){
setMessage("beklager, ingen worker");
}
function setMessage(msg){
document.getElementById("counter").innerHTML=msg;
}
</script>
</head>
<body>
<button onclick="setMessage('Hallo');">Hello</button>
<div style="font-size:32px" id="counter"> </div>
<p><a href="javascript:history.back()">Tilbake</a></p>
</body>
</html>
Skriptet til workeren, test2Work.js, ser slik ut:
// counting seconds
var start=0;
var counter=0;
this.onmessage = function(event) {
counter=event.data;
start=new Date().getTime();
setTimeout(Count,100);
}
function Count()
{
var now=new Date().getTime();
if((now-start) > 1000){
start=now;
counter--;
if(counter <= 0){
postMessage('done');
self.close();
return;
}
postMessage(counter);
}
setTimeout(Count,100);
}
test2.html
https://borres.hiof.no/wep/js/workers/wrk2/test2.html