1

When I was working on the problem of differentiating between on a single click and a double click on the same element in plain JavaScript (no JQuery), I saw this solution given by @Garland Pope and translated it to plain JavaScript:

var numClicks = 0,
  interval = null,
  delay = 250;
document.addEventListener("click", function(event) {
  numClicks++;
  if (numClicks === 1) {
    interval = setTimeout(function() {
      // Things to do on one click.
      console.log("Single Click");
      numClicks = 0;
    }, delay);
  } else {
    clearTimeout(interval);
    // Things to do on double click.
    console.log("Double Click");
    numClicks = 0;
  }
});

But when I changed the setTimeout and clearTimeout to setInterval and clearInterval respectively I did not get the expected result. With setTimeout, for two clicks within the "delay" time, it logged "Double Click" and for single click within the "delay" time, it logged "Single Click" only once.

But with setInterval, the same story goes with the double click. But, the difference comes with the single click. When I click once within the "delay" time, it logs "Single Click" but many times and never stops. Which is not what I wanted.

Can anyone explain why this happened? I have no idea.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shashank
  • 503
  • 1
  • 5
  • 7

1 Answers1

0

You don't need setInterval here, it will break all logic.
setTimeout - its timer that calls function once.
setInterval - its timer that calls function every seconds.

You make click, then application starts timer and waits. If no more clicks it will say 'single click'

Here example, that will workm but it emulate setTimeout function

var numClicks = 0;
var interval = null;
var delay = 250;

document.addEventListener('click', function () {
++numClicks;

if (numClicks === 1) {
    interval = setInterval(function () {
        clearInterval(interval);

        // Things to do on one click.
        console.log('Single Click');
        numClicks = 0;
        
    }, delay);
} else {
    clearInterval(interval);

    // Things to do on double click.
    console.log('Double Click');
    numClicks = 0;
}
});
Hyper
  • 327
  • 1
  • 5
  • 11