IronicUsername
IronicUsername

Reputation: 3

Wait until user is finished clicking | JavaScript

I want to count the clicks while the user keeps clicking. After about half a second when there are no more clicks on a specific button, the function should return the accumulated clicks.

I've tried it with this but, doesn't really work:

HTML:

<a href="javascript:void(0)" class="label" @click="cntNav">Next</a>

JavaScipt:

cntNav(element){
   let btn = element.target
   let cnt = 0
   let t = setTimeout(function(){
      console.log(cnt)
   }, 1000)

   btn.addEventListener("click", function(){
      cnt++
   })
}

Console Output (after 5x clicking):

4
3
2
1
0

Upvotes: 0

Views: 968

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48723

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>

Upvotes: 2

Leaf the Legend
Leaf the Legend

Reputation: 481

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.

Upvotes: 1

Related Questions