Brett
Brett

Reputation: 49

clearTimeout() not acting as expected

I have a menu with a submenu that slides out when you click on a button. I want it to slide back in after 7s if it hasnt already been clicked back in. I want to reset the timer when it is clicked back in so that it starts at the beginning if it is clicked again.

    $(".connect").click(function(){
     if($(".slidy-social").css("right") === "0px"){
       $(".slidy-social").animate({right: "200px"}, 250);
       var timer = setTimeout(function(){
         if($(".slidy-social").css("right") !== "0px"){
           $(".slidy-social").animate({right: "0px"}, 250)
         }
       }, 7000)
     }
     else{
       clearTimeout(timer);
       $("#social").animate({right: "0px"}, 300);
     }
   })

Upvotes: 0

Views: 42

Answers (1)

Barmar
Barmar

Reputation: 782498

The problem is that you're creating a new timer variable every time the click listener function is called. You need to declare the variable outside the function so it will be the same variable each time.

var timer;
$(".connect").click(function() {
  if ($(".slidy-social").css("right") === "0px") {
    $(".slidy-social").animate({
      right: "200px"
    }, 250);
    timer = setTimeout(function() {
      if ($(".slidy-social").css("right") !== "0px") {
        $(".slidy-social").animate({
          right: "0px"
        }, 250)
      }
    }, 7000)
  } else {
    clearTimeout(timer);
    $("#social").animate({
      right: "0px"
    }, 300);
  }
})

Upvotes: 1

Related Questions