Skip to content

Instantly share code, notes, and snippets.

@tango238
Created August 26, 2011 08:49
Show Gist options
  • Save tango238/1173000 to your computer and use it in GitHub Desktop.
Save tango238/1173000 to your computer and use it in GitHub Desktop.
[HTML5]WebWorkers
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>WebWorkers</title>
</head>
<body>
<section id="wrapper">
<header>
<h1>WebWorkers</h1>
</header>
<article>
Input Number:<input type="text" id="num" value="1000000000">
<button id="btnCalc">Calculate</button>
</article>
<script>
(function(){
// Workerを生成
var worker = new Worker('worker.js');
// Workerから結果を受け取る
worker.onmessage = function(event) {
// event.dataでWorkerからのデータを受け取る
alert("Sum:" + event.data);
};
var btnCalc = document.getElementById('btnCalc');
btnCalc.onclick = function(){
var num = parseInt(document.getElementById('num').value);
// ワーカに数値を渡す
worker.postMessage(num);
};
})();
</script>
</section>
</body>
</html>
// onmessageでメッセージを受け取る
onmessage = function(event) {
// event.dataでWorkerに渡されたデータを受け取る
var num = event.data;
var result = 0;
for (var i = 0; i <= num; i++) {
result += i;
}
// 結果を返す
postMessage(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment