Ari
Ari

Reputation: 6149

Adding a time limit on button click before running function incase button is clicked multiple times

I have a button that toggles an objects "status" value

1, 2, 3, 4

Each time the user clicks it cycles to the next value then back to the start. Each click, it also sends the updated value to the database. To limit these requests I wanted to add a buffer window where the user can rapidly cycle through, and only when they've stopped for say, 2 seconds, it then performs the function to send a request to update the value.

Current code HTML

<button v-on:click="changeStatus(item)">Status</button>

JavaScript

changeStatus: function (item) {

    if (item.status < 4) {
        item.status++;
    } else {
        item.status = 1;
    }
// Add some delay buffer here
     this.updateDatabase(item);
 },

Using VueJS, but the fundamental idea should still be the same.

Upvotes: 0

Views: 734

Answers (4)

StackSlave
StackSlave

Reputation: 10627

I would create a Waiter constructor that you can use in any Event. Just create a new instance for another Waiter:

addEventListener('load', ()=>{

function Waiter(milliseconds){
  let yes = true;
  this.wait = func=>{
    if(yes){
      func(); yes = false;
      setTimeout(()=>{
        yes = true;
      }, milliseconds);
    }
    return this;
  }
}
const testWaiter = new Waiter(2000);
document.getElementById('test').onclick = function(){
  testWaiter.wait(()=>{
    console.log(this.id);
  });
}

});
<input id='test' type='button' value='click here' />

Upvotes: 1

ariel
ariel

Reputation: 16150

Set a timer with setTimeout:

var updateTimer; // Global

...

changeStatus: function (item) {
  ...

  clearTimeout(updateTimer); // Unset previous timer, if any
  updateTimer = setTimeout(updateItem, 2000);
}

updateItem: function() {
  this.updateDatabase(item);
}

Upvotes: 2

Ari
Ari

Reputation: 6149

My solution based on Ariel's response, more vue specific.

I had to make the timer global in the data:

let app = new Vue({
    el: '#app',
    data: {
        updateTimer: "",
    },
    methods: {

    doSomething: function (item) {

        // Do immediate actions here


        clearTimeout(this.updateTimer);
        this.updateTimer = setTimeout(function(){
            // Do buffered/delayed actions here
            app.updateDatabase(item)
        }, 2000);


      },

    }
})

Upvotes: 0

xTrimy
xTrimy

Reputation: 813

You can save the last click time and compare it to the current time:

var lastClickedTime = 0

document.getElementById('myButton').addEventListener('click',function(){
  var timeNow = new Date();
  var difference = timeNow - lastClickedTime;
  difference = difference / 1000;
  if(difference >= 3){ // 3 Seconds
    console.log("Last click was "+difference+" seconds ago");
  }
  lastClickedTime = new Date();
});
<button id="myButton">Click Me</button>

Upvotes: 1

Related Questions