Reputation: 356
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">
Upvotes: 0
Views: 280
Reputation: 24965
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.
Upvotes: 1