开发者

JQuery wait for x sec. of inactivity before calling function

开发者 https://www.devze.com 2023-04-12 18:12 出处:网络
I have a form with multiple buttons, sliders, etc. that all trigger a main ajax pricing function when clicked, dragged, etc. Often a button is clicked multiple times consecutively in a short amount of

I have a form with multiple buttons, sliders, etc. that all trigger a main ajax pricing function when clicked, dragged, etc. Often a button is clicked multiple times consecutively in a short amount of time (e.g. a + button to increase a value开发者_如何转开发).

Instead of calling the main ajax function each time, I would like JQuery to wait for 1 sec after the LAST trigger event is done before executing. In other words, if the function is triggered < 1s since the last trigger... wait.


I would do a setTimeout call each time something changes, and set the timeout to 1000 ms. Store the returned value from the setTimeout call, and if a change occurs before the setTimeout call fires its callback, cancel the setTimeout and start another one.

var priceAdjustmentTimeout;
function somethingChanged() {
  if (priceAdjustment) {
    clearTimeout(priceAdjustmentTimeout);
  }
  priceAdjustmentTimeout = setTimeout(doPriceAdjustment, 1000);
}

function doPriceAdjustment() { 
  priceAdjustmentTimeout = null;
  /* do stuff here */
}


You can achieve this using a boolean variable as a flag, and using setTimeout. It might look like something like this.

var wait = false;
$('#button').click(
     function() {
         if(!wait) {
             //run code here
             wait = true;
         } else {
           var t = setTimeout('some code here ending with `wait = false;`',1000);
        }
     }
);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号