How to send a number to webworker ?
How to receive a number in webworker ?
if possible, How to do this without using json or javascript Object, because using it will add extra line of code ..
EDIT :
ew i got many downvote without knowing why .. i explain what i try to do..
i try to create timer in webworker
- if i send string "start" to webworker, webworker will begin the interval( the timer )
- if i send a number to webworker, webworker will set the duration of interval
but i don't know how to send a number,
i knew argument passed to webworker should be a string, i already read few tutorial,
but i still don't understand what to do so my webworker can recognize a number..
because i try parseInt() and is not work ..
here's my code
in HTML
window.onload = function(){
var worker = new Worker("Thread.js");
worker.postMessage("1500"); //set duration of interval
worker.postMessage("start"); //start the interval
worker.onmessage = function(e){
document.body.innerHTML += '<p> worker receive: '+e.data+'</p>';
}
worker.onerror = function(e){
document.body.innderHTML += "<p> worker error"+e.data+"</p>";
}
}
Thread.js
onmessage = function(e){
var msg = e.data ;
var timer;
var duration = 1000; //default duration
try{
var number = parseInt(msg);
msg = number;
}catch(e){
}
//start the interval
if(msg === "start"){
timer = setInterval(function(){
postMessage( "lalala" );
}, duration);
}
else if(msg === "stop"){
clearInterval(timer);
}
//set duration
else if(!isNaN(msg)){
duration = msg;
}
}