jQuery等待x秒.调用函数之前的不活动状态 [英] JQuery wait for x sec. of inactivity before calling function

查看:49
本文介绍了jQuery等待x秒.调用函数之前的不活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个按钮,滑块等的表单,当它们被单击,拖动等时,它们都会触发主要的ajax定价功能.通常在短时间内连续多次单击一个按钮(例如,一个+按钮增加一个值).

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).

我希望JQuery在LAST触发事件完成后等待1秒钟,然后再执行一次,而不是每次都调用main ajax函数.换句话说,如果功能被触发,则<自上次触发以来1秒钟...等待.

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.

推荐答案

每次更改时,我都会进行一次setTimeout调用,并将超时设置为1000毫秒.存储从setTimeout调用返回的值,如果在setTimeout调用触发其回调之前发生更改,请取消setTimeout并启动另一个.

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

这篇关于jQuery等待x秒.调用函数之前的不活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆