Pls help i want to stop and reset
function likeButtonFunction () {
if (unlikeText.classList.contains('not-active')) {
likeText.classList.add('not-active');
unlikeText.classList.remove('not-active');
let myInterval = setInterval(hearts, 100);
return myInterval;
}
else if (likeText.classList.contains('not-active')) {
unlikeText.classList.add('not-active');
likeText.classList.remove('not-active');
myInterval = clearInterval(myInterval, 0);
clearInterval(myInterval);
}
}
likeButton.addEventListener('click', likeButtonFunction);
I tried clearInterval() but it didnt work
2
Answers
The variable
myInterval
does not exist in the else block.What you have to do is to define it in global scope.
With the modified code above, you will have a global variable called
myInterval
, what can be used to track the interval object.It’s type is
number | undefined
in TS.The DOM modifications + interval starting happens if bot the conditions present (the interval is not defined and the class is not added to the element). Same applies for the else statement (if the interval is present and the class is present as well).
Please not that
setInterval()
returns numbers starting from1
so the falsyness check works, but if you’d like to prettify your code you can addmyInterval === undefined
to the check block.