Search code examples
javascripttimeoutsettimeoutsetintervalcleartimeout

Clear 'looped' timeout closed in function - how to return id of interval that I would have ability to clear it


I have two functions inside my Class. First fires timeout and looped it (works like interval) and second to clearTimeout. My problem is, that clearTimeout doesn't work. How can I fix it?

this.startMove = function() {
    setTimeout(function handler() {
        self.moveMonster(moveMonsterCallback);
        setTimeout(handler, self.speed);
    }, this.speed);
};

this.stopMove = function() {
    clearTimeout(self.startMove());
}

For example I want to run these functions on click.


Solution

  • Let me know if this works for you :

    this.startMove = function() {
        self.timeout = setTimeout(function handler() {
            self.moveMonster(moveMonsterCallback);
            self.startMove();
        }, self.speed);
    };
    
    this.stopMove = function() {
        clearTimeout(self.timeout);
    }
    

    So basically I have reused the @Michael Horn's solution. And, I am happy to use this answer as an to his edited answer (if the question resolves).