Reputation: 1801
So in my code, if an element is not doing something [playing
] then I'll start playing it. If it's playing, stop the thing. I managed to make it start playing but it never stop.
var playing = false;
var current = 30;
$('#countDownContainer').click(function() {
if (!playing) {
playing = false;
setInterval(function() {
$('#workSpace label').get(0).innerHTML = current;
current -= 1;
},1000);
} else {
playing = true;
}
});
In theory, when user click #countDownContainer
,playing
would be set to false and run the setInterval
code and if it's already playing, playing
would be set to true and when go through the loop it wouldn't run. But in fact, it keep changing from 30
to 29
and back to 30
.And it never stop when I clicked the button again. please help -thanks
Upvotes: -1
Views: 76
Reputation: 6830
First of all, I think you have mixed up your var playing
assignments.
You should also assign the ID returned from setInterval
so you can later abort that intervalled loop with clearInterval
:
//initialize var at the start of the script
var intervalID;
// in the onclick event
if (!playing) {
playing = true; // should be true here
intervalID = setInterval(function() {
$('#workSpace label').get(0).innerHTML = current;
current -= 1;
},1000);
} else {
playing = false; // should be false here
clearInterval(intervalID);
}
See the documentation on clearInterval
Upvotes: 1
Reputation: 21150
This is called a logic error.
Because note the following:
var playing = false; // playing is initialised to false
if (!playing) { // if not playing
playing = false; // set playing to false
Hence playing
can never become true
.
You can solve by doing the following:
var playing = false;
var current = 30;
$('#countDownContainer').click(function() {
if (playing) {
playing = false;
} else {
playing = true;
setInterval(function() {
$('#workSpace label').get(0).innerHTML = current;
current -= 1;
},1000);
}
});
Or in words:
If not playing
, we make it playing hence: playing = true;
If playing
, we make it not playing hence: playing = false
Addendum
For the stop problem, please refer to @Riturajratan his question.
Upvotes: 1
Reputation: 10378
var clear= setInterval(function() {
$('#workSpace label').get(0).innerHTML = current;
current -= 1;
},1000);
clearinterval(clear);// to stop interval where you want
//clearInterval(id_of_setinterval)
reference clearInterval
Upvotes: 1