如何使设置超时在上次单击切换时激活



我正在使用.slideToggle在单击图像后显示div。我希望div 在上次单击切换开关后 10 秒消失。问题是,如果我单击图像几次,持续时间是第一次单击后的 10 秒,而不是最后一次。如果您查看小提琴(我使用了较短的持续时间进行测试(并单击图像几次,您将明白我的意思。

有没有人知道我如何才能让它按预期工作?任何帮助将不胜感激!

小提琴:https://jsfiddle.net/7fy536nv/

要求。。。

  • div 应该显示 10 秒,然后消失
  • 如果再次单击图像,div 将消失
  • 如果单击div 外部的内容,div 将消失

.HTML

<div class="box-new">
    <a href="box-link" id="box-link">
        <img src="https://dummyimage.com/100x60/ff0000/fff.png">
    </a>
</div>
<div id="empty-box">jkhsahg akjfhsajk fhas jklsad flkasd hfjkashd fjka sdkjfh adskjfhs dakjfh kafh sdah dhjaf</div>

.CSS

body, html {
    margin: 0;
}
#empty-box {
    display: none;
    position: absolute;
    background: #000;
    top: 60px;
    width: 240px;
    padding: 20px;
    left: 0;
    color: #fff;
    text-align: center;
    font-family: "open sans", "arial";
    font-size: 14px;
    font-weight: 600;
    line-height: 18px;
    z-index: 1;
}

.JS

$('#box-link').click(function(event){
    event.stopPropagation();
    $("#empty-box").slideToggle(400);
    setTimeout(function() { 
        $("#empty-box").slideUp(); 
    }, 5000);
    return false;
});
$("#empty-box").on("click", function (event) {
    event.stopPropagation();
});
$(document).on("click", function () {
    $("#empty-box").slideUp(400);
});

将调用分配给外部作用域中声明的变量setTimeout,并在每个后续事件中使用 clearTimeout 清除它:

var timeout;
$('#box-link').click(function(event){
    clearTimeout(timeout);
    event.stopPropagation();
    $("#empty-box").slideToggle(400);
    timeout = setTimeout(function() { 
        $("#empty-box").slideUp(); 
    }, 5000);
    return false;
 });

setTimeout函数返回一个值,您可以使用 clearTimeout 取消该值。

因此,在您的代码中,存储返回值,每次单击它时,取消以前的超时并重新启动新的超时。

var timeout = null;
function test()
{
    if( timeout !== null )
          clearTimeout(timeout);
    timeout = setTimeout(..., 10000);
}

这很简单,真的。关键是将设置超时放在variable中并调用clearTimeout(variable)

例:

let someVar = false,
    someTime = 5000,
    msgTimer = document.getElementById('timer'),
    timer, 
    current,
    displayTimer = false;
$('.yourButton').on('click', someFunc)
function someFunc() {
  if (someVar) {
    clearTimeout(someVar)               // <<< juice is here
    console.log('cleared timeout!')
  }
  timer = performance.now()
  someVar = setTimeout(function () {
    clearInterval(displayTimer)
    console.log(someTime / 1000 + 
    ' seconds passed since last click...')
    someVar = false
    displayTimer = false
    msgTimer.innerHTML = ''    
  }, someTime)
  /**
   * ¯_(ツ)_/¯
   * ignore past this point, rest is timer
   *
   * ˙ʇᴉ pǝǝu ʇ,uop no⅄ ˙ʎllɐǝɹ
   **/
  if (displayTimer) { 
    clearInterval(displayTimer)
    displayTimer = false
  }
  displayTimer = setInterval(function () {
    current = performance.now()
    msgTimer.innerHTML = Math.max(timer + 5000 - current,0)
    .toFixed(2) + 'ms'
  }, 15)
}
#timer {
  font-family: monospace;
  text-align:right;
  display: inline-block;
  width: 100px;
  font-size: 1.2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="yourButton">Don't click. Think.</button>
<span id="timer"></span>

间隔缩短至 5 秒,测试速度更快。

这是一个显示最多 10 秒div的解决方案......

如果用户在此延迟之前单击任意位置,请将其隐藏。
如果用户经常或反复点击,延迟没有问题......
因为我负责重置。

我创建了一个CodePen,在购物车链接旁边显示了一个计时器,以显示时间流逝。
这是一个CodePen,其代码与下面的代码片段完全相同,如果你想使用它。

var emptyCart = $("#emptyCart");
var cartTimer;
var carMaxTime = 10000;
// Function to hide the cart
var hideCart = function(){
  emptyCart.dequeue().slideUp("slow");
}
// Function to show the cart
var showCart = function(){
  emptyCart.dequeue().slideDown("slow");
  clearTimeout(cartTimer);            // Just to be sure We have only one timer running
  cartTimer = setTimeout(function(){
    hideCart();
  },carMaxTime);
}
// Function to handle click on the cart link
$("#clickCart").click(function(){
  $(document).off("click",hideCart());  // Just to prevent a slideUp which would counter-act a slideUp
  if(emptyCart.is(":hidden")){
    showCart();
  }
  setTimeout(function(){                // 1ms delay to use this event handler on next click.
    $(document).on("click",function(){
      hideCart();
      $(document).off("click",hideCart());  // Unbind this handler once used.
    });
  },1);
});
#emptyCart{
  display:none;
  width:100px;
  background:#000;
  color:#fff;
  height:30px;
  margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickCart">
  <a href="#">Cart</a>
</div>
<div id="emptyCart">
  No items
</div>

最新更新