Reputation: 357
I have a webworker and its working fine.
webworker.js :
//portion of webworker.js
self.onmessage = function(evt){
if(evt.data == "start"){
var i = 0;
var mytimer = setInterval(function(){
i++;
postMessage(i);
},1000);
}
if(evt.data == "stop"){
clearInterval(mytimer);
}
}
but clear interval is not working. Am i missing something?
Upvotes: 1
Views: 972
Reputation: 24567
As others have said, the problem is with the scope of the mytimer
variable.
If you want to avoid cluttering up the global namespace, you could store it as a static variable using this hack:
self.onmessage = function(evt){
if(evt.data == "start"){
var i = 0;
arguments.callee.mytimer = setInterval(function(){
i++;
postMessage(i);
},1000);
}
if(evt.data == "stop"){
clearInterval(arguments.callee.mytimer);
}
}
Upvotes: 0
Reputation: 224942
mytimer
is local to your function. If you want it to persist across calls to onmessage
, you need to move it to some outer scope:
var mytimer;
self.onmessage = function(evt) {
if (evt.data == "start") {
var i = 0;
mytimer = setInterval(function() {
i++;
postMessage(i);
}, 1000);
} else if (evt.data == "stop") {
clearInterval(mytimer);
}
};
Upvotes: 7