KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 2 months ago 9
jQuery Question

JQuery clearInterval refuse to working

I have a jQuery

function
that when it runs a
setInterval function
is called and a div is also
display:block;
But I want the interval to stop when the div is
display:none
. I tried 3 different attempts. The first attempt says
stp not defined
and
strt not defined
in my
console.log
, but the other 2 isn't working.


  1. First Attempt

    function runner(){
    document.getElementById("x").style.display='block';
    var strt = setInterval (function(){
    $("div").show();
    }, 1000);
    var stp = setInterval (function(){
    $("div").hide();
    }, 1000);
    }

    //then I attempt to clearInterval outside the runner function

    x = document.getElementById("x");
    if(x.style.display == "none"){
    clearInterval(stp);
    clearInterval(strt);
    }

  2. Second Attempt

    function runner(){
    document.getElementById("x").style.display='block';
    var strt = setInterval (function(){
    $("div").show();
    }, 1000);
    var stp = setInterval (function(){
    $("div").hide();
    }, 1000);

    // I attempt to clearInterval inside the runner function

    x = document.getElementById("x");
    if(x.style.display == "none"){
    clearInterval(stp);
    clearInterval(strt);
    }
    }

  3. Final Attempt

    function runner(){
    document.getElementById("x").style.display='block';

    // I attempt to clearInterval inside the setInterval function

    var strt = setInterval (function(){
    x = document.getElementById("x");
    if(x.style.display == "block"){
    $("div").show();
    } else {
    clearInterval(strt);
    }
    }, 1000);

    var stp = setInterval (function(){
    x = document.getElementById("x");
    if(x.style.display == "block"){
    $("div").hide();
    } else {
    clearInterval(stp);
    }
    }, 1000);

    }


    My aim is when the
    runner function
    is running the the
    div
    keeps on blinking off and on every 1sec and I want it to stop as soon as
    x.style.display == "none"
    Please How do I run my code?


Answer

I have figured out the issue. The first attempt works fine but I need to define the strt and stp variables before running the function like this

var start;
var stp;
function runner (){
    //blah blah blah
}