Reputation: 73
I am designing a button. The text on the button is "run" at the beginning. If I click it the text turns into "stop" and it triggers a setInterval event. However, I have trouble about how to stop this event. In the following code, I declare run variable at the beginning; in the if statement, I set it to a setInteval, but the run variable shows undefined in the else branch, making the clearInterval function not working as expected. How do I solve this problem?
$("#run").click(function(){
var $this = $(this);
var run;
if($this.text() === "run"){
run = setInterval(()=>{
model.run();
},50);
$this.text("stop");
}
else{
clearInterval(run);
$this.text("run");
}});
Upvotes: 3
Views: 75
Reputation: 2881
Your code is working fine.
$("#run").click(function(){
var $this = $(this);
var run;
if($this.text() === "run"){
run = setInterval(()=>{
// model.run();
},50);
$this.text("stop");
}
else{
clearInterval(run);
$this.text("run");
}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="run">run</button>
Upvotes: 0
Reputation: 20944
The handler function of your click
event is being run every time you click. That also means that any variable in that function that you define, is being redefined. Put your run
variable outside of the click function scope.
var run;
$("#run").click(function(){
var $this = $(this);
if($this.text() === "run"){
run = setInterval(()=>{
model.run();
},50);
$this.text("stop");
}
else{
clearInterval(run);
$this.text("run");
}
});
Or if you don't want any global variables hanging around, use closures.
$("#run").click((function(){
var run;
return function() {
var $this = $(this);
if($this.text() === "run"){
run = setInterval(()=>{
model.run();
},50);
$this.text("stop");
}
else{
clearInterval(run);
$this.text("run");
}
}
}()));
Upvotes: 5