Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created April 22, 2012 09:43
Show Gist options
  • Save lamprosg/2463105 to your computer and use it in GitHub Desktop.
Save lamprosg/2463105 to your computer and use it in GitHub Desktop.
HTML5 Web Workers example
var i=0;
function timedCount()
{
i=i+1;
postMessage(i); //posts a message back to the HTML page.
setTimeout("timedCount()",500);
}
timedCount();
<!-- When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. -->
<!-- A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting -->
<!-- the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., -->
<!-- while the web worker runs in the background. -->
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br /><br />
<script>
var w;
function startWorker()
{
if(typeof(Worker)!=="undefined") //check whether the user's browser supports it
{
w=new Worker("demo_workers.js"); //creates a new web worker object and runs the code in "demo_workers.js"
//Add an "onmessage" event listener to the web worker
//When the web worker posts a message, the code within the event listener is executed. The data from the web worker
//is stored in event.data.
w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; };
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
}
function stopWorker()
{
w.terminate(); //terminate a web worker, and free browser/computer resources
}
</script>
</body>
</html>
@lamprosg
Copy link
Author

IE is not supported.

@ahmedkhonji
Copy link

rep: lamprosg:

thats why it coded as:

if(typeof(Worker)!=="undefined") //check whether the user's browser supports it
{
//do the web worker
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";

}

@ahmed-issa-mohd
Copy link

google chrome is not supported !!!

@ahmed-issa-mohd
Copy link

why does not work on google chrome ?

@ahmed-issa-mohd
Copy link

Yes! Web worker support!

@ahmed-issa-mohd
Copy link

@ahmed-issa-mohd
Copy link

this example does not work on my editor

@ahmed-issa-mohd
Copy link

do you know why ?

@ahmed-issa-mohd
Copy link

image

@ventseslav8
Copy link

IE ask me to allow activeX controls and scripts and then run it normally. Maybe chrome have similar problem, but I couldn`t find the right options.

@alimahatma
Copy link

try to run using "iternet explorer" cause crome doesn't support it

1
2

@ch4t88
Copy link

ch4t88 commented Jul 7, 2023

why extension error ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment