简体   繁体   English

jQuery延迟触发事件

[英]jQuery trigger event with delay

I have a situation in which I have a series of buttons on a page. 我遇到的情况是页面上有一系列按钮。 Clicking a button triggers several functions and runs a series of complex calculations. 单击一个按钮将触发多个功能并运行一系列复杂的计算。

Then I have what is essentially a "click all" button that will trigger a click event on each button: 然后,我实际上是一个“全部单击”按钮,它将触发每个按钮的点击事件:

$('.myBtn').trigger('click'); // $('.myBtn') returns a list of all buttons

This works fine in most modern browsers, but in IE the trigger('click') takes a long time to run and I often get a 'script is taking too long' error. 这在大多数现代浏览器中都可以正常工作,但是在IE中,trigger('click')需要花费很长时间才能运行,并且我经常会收到“脚本花费的时间太长”的错误。

Unfortunately, the way things are set up there's no real way to avoid the heavy calculations on click. 不幸的是,事情的设置方式并没有真正的方法来避免点击时的繁琐计算。

So I'm thinking of adding some sort of delay. 因此,我正在考虑增加某种延迟。 So on "click all", trigger btn1 click , wait 200ms, trigger btn2 click , wait... etc. 因此,在“单击全部”上,触发btn1 click ,等待btn2 click毫秒,触发btn2 click ,等待...等等。

I've tried things like: 我已经尝试过类似的事情:

$('.btnAll').each(function() {
    var el = $(this);
    setTimeout(function () {
        el.trigger('click');
    }, 200);
});

But I don't think this works correctly because of the way .each() calls are queued or something(?). 但是由于.each()调用排队或某事(?)的方式,我认为这无法正常工作。 Event queueing and synchronous calls are still a little unclear to me. 对我来说,事件排队和同步调用仍然有点不清楚。

Any thoughts on how I can make this work? 关于如何进行这项工作有任何想法吗?

.each() calls are not 'queued', they just execute the given function on each element of the collection, one after the other. .each()调用不会“排队”,它们只是在集合的每个元素上一个接一个地执行给定的功能。 So you set for each button-click a timeout of 200ms. 因此,您为每个按钮单击设置了200ms的超时时间。 The result: 200ms later all buttons are triggered at (nearly) same time. 结果:200ms之后(几乎)同时触发了所有按钮。 If you want to stagger the clicks with delay in between, you must give them different times like so: 如果要在两次点击之间延迟延迟,请给它们不同的时间,例如:

$('.btnAll').each(function(i) { // i is index of this in the collection
    var el = $(this);
    setTimeout(function () {
        el.trigger('click');
    }, i * 200); // each button gets a multiple of 200ms, depending on its index
});

This triggers the first button immediately, the second 200 ms later, the third.... . 这将立即触发第一个按钮,第二个200毫秒后触发第三个按钮。

Try it 试试吧

function myEach(){
  $('.btnAll').each(function() {
       $(this).trigger('click');
  });
}

setTimeout(myEach(),200);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM