Is it possible for the click delay to restart on a new click

177
November 22, 2016, at 09:18 AM

I have a list of ZIP codes that will each have a checkbox next to them. When the user checks or unchecks a ZIP, I'm redrawing a map that has the ZIP polygons drawn onto it. Instead of telling the map to redraw each and every time a class of "polyZIP" is clicked, I'd like to do a delay where the map is drawn 1 second after the click... but there's the part I'm unsure of. If the user goes down the list and rapidly checks/unchecks ZIP codes, I'd like each click to restart the 1 second timer so that the map will only be redrawn once the clicking has stopped for at least a second.

I created a (very ugly) test at http://jsfiddle.net/a2f1ydyh/. You can see on the fiddle that if you rapidly click the go button, eventually the results area will count each and every click. I'd like it basically that any click would restart the counter.

Here's the ugly code:

<script>
    var counter = 0;
    var timeout = "";
    $(function() {
        $("#go").click(function() {
            timeout = setTimeout(function() { actionFunction(); }, 3000);
        });
    });
    function actionFunction()
    {
        counter++;
        var results = $("#results").html() + "<br />" + counter;
        $("#results").html(results);
        clearTimeout(timeout);
    }
</script>
<input id="go" type="button" value="CLICK ME" /><br /><br />
<div id="results"></div>
Answer 1

Clear the timeout before you set the new one in your click function.

var counter = 0; 
var timeout = ""; 
$(function() { 
  $("#go").click(function() { 
    clearTimeout(timeout); 
    timeout = setTimeout(function() { 
      actionFunction(); 
    }, 3000); 
  }); 
}); 
 
function actionFunction() { 
  counter++; 
  var results = $("#results").html() + "<br />" + counter; 
  $("#results").html(results); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<input id="go" type="button" value="CLICK ME" /> 
<br /> 
<br /> 
 
<div id="results"></div>

READ ALSO
Multiple upload files with ajaxForm plugin

Multiple upload files with ajaxForm plugin

I used the ajaxForm plugin to make multiple upload. The upload works perfectly, even can add files to the list and remove.

181
What&#39;s the best way to loop over an array in JSON?

What's the best way to loop over an array in JSON?

So I have a JSON file that has a departures array within it. I'd like to loop over each bus line and display them in div's like so:.

123
bxSlider breaking after show()

bxSlider breaking after show()

I'm using bxSlider on ticker mode and have a pair of buttons that respectively hide and show it with.

185
jQuery show one next sibling at a time on click

jQuery show one next sibling at a time on click

I'm trying to show hidden rows one at a time on button click, but they all show at once since they have class "row" - the 1st row is shown by default and the rest are hidden.

130