clearInterval does not work


It is basically a slider that works except the fact it keeps running whereas the user has clicked on a dot.

I would like to understand why my clearInterval does not work in this following piece of code. Thank you very much for any ideas.

let myBigFunction = (isDotClicked) { 

  let x;  //Initialize my var for the interval

// Function sliderArticles that will be called every 3000s
  let sliderArticles = () => {

            newDiv.innerHTML = markupSlidersArticle[indice];
            locations.parent.insertBefore(newDiv, locations.sibiling);
            if (indice >= markupSlidersArticle.length) {
                indice = 0;

//My logic 
        if (isDotClicked >= 0) {
            console.log("fired")  // It does fire when  users click an element(dot)
            let child = document.getElementsByClassName("section_contenant")[0];
            child.innerHTML = markupSlidersArticle[indice];
            clearInterval(x) // It does not do my expectation.
            x = 0; // to make sure to cancel the interval
        } else {
            x = setInterval(sliderArticles, 3000)  // set my interval

You need to put x outside of the function, because otherwise it gets re-initialized every time.

Why? X it is outside of the scope of the function sliderArticles. (I have re-written the code quickly to emphasise the scope of x)

I put X outside of the big function and it does work, thank you. I need to spend sometime to figure out why. I though because X was not sharing the same scope of if and else it would have produce the same result as the let x is finally rewritten inside the scope of (if (isDotClicked >= 0) and the “return” ends the global function.