A
A
artem782017-02-14 03:53:09
JavaScript
artem78, 2017-02-14 03:53:09

Why doesn't the timer stop?

The method startcreates a timer that executes the function the desired number of times. If the end is reached, the method is called stop, in which the timer stops..

function Worker(opts) {
  // ...

  this.start = function() {
    //console.log(interval);
    if (working) return;
  
    position = 0;
    timer = window.setInterval(function() {
      //console.log('timer');
      position += step;
      on_step(position, from, to);
      if (position >= to) {
        console.log('end1');
        self.stop();
      }
    }, interval);
    on_start();
    working = true;
    on_step(position, from, to);
  };
  
  this.stop = function() {
    сonsole.log('end2');
    if (!working) return;
    
    //console.log(timer);
    window.clearInterval(timer);
    working = false;
    on_end();
  };

  // ...
}

For some reason, the timer doesn't stop. There is no call stop()- firebug writes to the console end1, but end2no. Doesn't output any errors.
https://jsfiddle.net/crazzy/o940649p/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2017-02-14
@artem78

Because self.stop();, and at the same time, the variable self is not declared.
So it works: https://jsfiddle.net/o940649p/2/
PS: Once I did a similar thing, you can see https://jsfiddle.net/Stalk/mLu8v4k6/

M
Mikhail Plyusnin, 2017-02-14
@rpe4a

It is possible like this:

this.start = function() {
  	//console.log(interval);
  	if (working) return;
  
  	position = 0;
  	timer = window.setInterval(function(self) {
    	//console.log('timer');
    	position += step;
      on_step(position, from, to);
      if (position >= to) {
      	console.log('end1');
      	self.stop();
      }
    }.bind(null, this), interval);
    on_start();
    working = true;
    on_step(position, from, to);
  };

Or like this:
this.start = function() {
  	//console.log(interval);
  	if (working) return;
  
  	position = 0;
  	timer = window.setInterval(function() {
    	//console.log('timer');
    	position += step;
      on_step(position, from, to);
      if (position >= to) {
      	console.log('end1');
      	this.stop();
      }
    }.bind(this), interval);
    on_start();
    working = true;
    on_step(position, from, to);
  };

In all these intervals, the default context is the window variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question