user3015541
user3015541

Reputation: 357

clearInterval in webworker is not working

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

Answers (2)

r3mainer
r3mainer

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

Ry-
Ry-

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

Related Questions