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.