execute my setTimeout function after clicking stops

徘徊边缘 提交于 2019-12-25 00:14:17

问题


I have a click event where once you click the div, it is adding and removing classes from two other divs.

Then I have a setTimeout function where it is reversing the classes it added and removed from the two other divs.

The thing is, I need the setTimeout to execute after the clicking stops.

Is there a way to check for the click event to end before the setTimeout can execute?

Everything works but I need it to not do setTimeout until the clicking stops.

Here is my Code:

$(".plus").click(function() {
    $(".reg-state").removeClass("active");
    $(".reg-state").addClass("hidden");
    $(".hot-state").removeClass("hidden");  
    $(".hot-state").addClass("active");

    setTImeout(function() {
        $(".reg-state").removeClass("hidden");
        $(".reg-state").addClass("active");
        $(".hot-state").removeClass("active");           
        $(".hot-state").addClass("hidden");
    }, 2000);
});

<div class="plus"></div>
<img class="reg-state active" src="images/SVG/circle.svg">
<img class="hot-state hidden" src="images/SVG/circlered.svg">

回答1:


You're creating a new timeout for each click. If you want it to happen only after the click has stopped, you can try the following.

$(function() {
  var throttle = null;
  
  $(".plus").click(function() {
    if (throttle) clearTimeout(throttle);
    
    $(".reg-state").removeClass("active");
    $(".reg-state").addClass("hidden");
    $(".hot-state").removeClass("hidden");
    $(".hot-state").addClass("active");

    throttle = setTimeout(function() {
      throttle = null;
      
      $(".reg-state").removeClass("hidden");
      $(".reg-state").addClass("active");
      $(".hot-state").removeClass("active");
      $(".hot-state").addClass("hidden");
    }, 2000);
  });
});

This will destroy the timeout every time the user clicks the element, provided it's within 2 seconds, the time of your timeout.



来源:https://stackoverflow.com/questions/49076520/execute-my-settimeout-function-after-clicking-stops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!