Stop a Function with jquery?

Asked

Viewed 82 times

1

The problem is this. I have a function called auto() that opens a div after 6 seconds when the page loads, besides said there is a button that if it is clicked, does the same. But if I open and close before the 6 seconds pass, the function auto() rerun. There is a way that when I press the button, it cancels the other function to be executed?

My code is this:

function abre(){
    auto
    $("#noti").css("display", "block");
    $("#noti").animate({
        width: "100px"
    }, 500, function(){
       $("#noti").animate({
        height: "200px" 
    });
    });
    $(".left_noti2").animate({
        left: "100px"
    }, 500);
    $("#chevron").hide(0);
    $("#chevron2").show(0);
}
function fecha(){
    $("#noti").css("display", "block");
    $("#noti").animate({
        height: "50px"
    }, 500, function(){
        $("#noti").animate({
            width: "0px"
        })
    });
    $(".left_noti2").delay(500).animate({
        left: "0px"
    }, 500);
    $("#chevron2").hide(0);
    $("#chevron").show(0);
}

//Função que abre automaticamente
function auto(){
  setTimeout(function(){
      abre();
  }, 3000);
}


//chama as funções ao carregar nas divs
$("#abrir").click(abre);

$("#fecha").click(fecha);

1 answer

2


The setTimeout when invoked returns a pointer to stop it. So if you call the clearTimeout with this pointer as argument you interrupt the setTimeout. An example would be:

var espera = null;

function abre() {
  clearTimeout(espera);
  /// etc...
}

function fecha() {
  //...
}

//Função que abre automaticamente
var espera = setTimeout(abre, 3000);

//chama as funções ao carregar nas divs
$("#abrir").click(abre);
$("#fecha").click(fecha);
  • 1

    Thank you! It worked perfectly, I will give the answer as soon as I can

Browser other questions tagged

You are not signed in. Login or sign up in order to post.