[Vuejs]-Wait until user is finished clicking | JavaScript

2๐Ÿ‘

โœ…

You could create a timeout to delay returning the clicks.

const main = () => {
  new Clicker('#click-me', {
    timeout: 500,
    callback: (clicks) => console.log(`Clicks: ${clicks}`)
  });
};

class Clicker {
  constructor(selector, options) {
    this.reference = typeof selector === 'string' ?
      document.querySelector(selector) : selector;
    let opts = Object.assign({}, Clicker.defaultOptions, options);
    this.timeout = opts.timeout;
    this.callback = opts.callback;
    this.initialize();
  }
  
  initialize() {
    this.__clickCount = 0;
    this.__activeId = null;
    this.reference.addEventListener('click', e => this.handleClick())
  }
  
  handleClick() {
    this.__clickCount += 1;
    clearTimeout(this.__activeId); // Reset the timeout
    this.__activeId = setTimeout(() => {
      this.callback(this.__clickCount);
      this.__clickCount = 0; // Reset clicks
    }, this.timeout);
  }
}

Clicker.defaultOptions = {
  timeout: 1000
};

main();
<button id="click-me">Click me!</button>
๐Ÿ‘คMr. Polywhirl

1๐Ÿ‘

HTML:

<button onclick="cntNav();">Click Me!</button>

JS:

var cnt = 0;
var myTimeOut;
cntNav = function(){
   clearTimeout(myTimeOut);
   myTimeOut = setTimeout(function(){
      console.log(cnt);cnt=0;
   }, 1000)
   cnt++;
}

This removes the timeout whenever someone clicks, so if someone clicks before the timeout has called, then it will be cleared. It will only call when someone leaves enough time in-between clicks. This then also sets the count back to zero.

๐Ÿ‘คLeaf the Legend

Leave a comment