简体   繁体   English

clearTimeout()不能按预期运行

[英]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. 如果尚未单击它,我希望它在7秒后滑回。我想在重新单击它时重置计时器,以便如果再次单击它则从头开始。

    $(".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);
     }
   })

The problem is that you're creating a new timer variable every time the click listener function is called. 问题在于,每次单击侦听器函数时都在创建一个新的timer变量。 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);
  }
})

This is untested, as we do not have your markup or a fiddle example. 这未经测试,因为我们没有您的标记或小提琴示例。

But you could use the delay jQuery function instead of a timeout. 但是您可以使用delay jQuery函数代替超时。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM