JQuery wait for x sec. of inactivity before calling function

六月ゝ 毕业季﹏ 提交于 2021-01-29 04:49:05

问题


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.


回答1:


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 */
}



回答2:


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);
        }
     }
);


来源:https://stackoverflow.com/questions/7762520/jquery-wait-for-x-sec-of-inactivity-before-calling-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!