Stop a function with jquery?

1

The problem is as follows. I have a function called auto() that opens a div after 6 seconds when the page loads, in addition said there is a button that if clicked, it does the same. But if I open and close before the 6 seconds pass, the auto() function is executed again. Is there a way that when I click the button, it cancels the other function to be executed?

My code is as follows

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);
    
asked by anonymous 20.09.2017 / 19:13

1 answer

2

The setTimeout when invoked returns a pointer to the power to stop. So if you call clearTimeout with this pointer as argument you break 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);
    
20.09.2017 / 19:19