skip to Main Content

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


  1. let myInterval;
    function likeButtonFunction () {
        if (unlikeText.classList.contains('not-active')) {
            likeText.classList.add('not-active');
            unlikeText.classList.remove('not-active');
            myInterval = setInterval(hearts, 100);
        }
        else if (likeText.classList.contains('not-active')) {
            unlikeText.classList.add('not-active');
            likeText.classList.remove('not-active');
            clearInterval(myInterval);
        }
    }
    
    likeButton.addEventListener('click', likeButtonFunction);
    
    Login or Signup to reply.
  2. The variable myInterval does not exist in the else block.

    What you have to do is to define it in global scope.

    let myInterval = undefined;
    function likeButtonFunction () {
        if (!myInterval && unlikeText.classList.contains('not-active')) {
            likeText.classList.add('not-active');
            unlikeText.classList.remove('not-active');
            myInterval = setInterval(hearts, 100);
            return myInterval;
        }
        else if (myInterval && likeText.classList.contains('not-active')) {
            unlikeText.classList.add('not-active');
            likeText.classList.remove('not-active');
            if (myInterval) {
                clearInterval(myInterval);
                myInterval = undefined;
            }
        }
    }
    
    likeButton.addEventListener('click', likeButtonFunction);
    

    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 from 1 so the falsyness check works, but if you’d like to prettify your code you can add myInterval === undefined to the check block.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search