JSFiddle - React, Tailwind, and code Playground
HTML
<button id="bugStop">stop bug</button>
JavaScript
function npc(name) {
this.name = name;
this.grid = [[0,9], [0,9]];
this.position = [0,0];
//Where the code was modified:
this.handle;
this.start = function() {
this.handle = setInterval(
(function(self) {
return function() {
self.move();
//if(self.position[1]==1) self.stop(self.handle);//Stop on some condition
}
})(this), 1000);
};
this.stop = function(handle) {
console.log("time to stop");
clearInterval(handle);
}
//End of modifications
this.move = function() {
this.position[0] = this.position[0] + Math.floor(Math.random() * 2);
this.position[1] = this.position[1] + Math.floor(Math.random() * 2);
if (this.position[0] > this.grid[0][1] || this.position[1] > this.grid[1[1]]) {
this.position = [0,0];
};
console.log(this.name + " moved to " + this.position);
}
}
var bug = new npc("test-name");
bug.start();
//Add event handler
document.getElementById("bugStop").addEventListener("click", function(){
bug.stop(bug.handle);
});