Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  10] [ 4]  / answers: 1 / hits: 6758  / 10 Years ago, fri, november 7, 2014, 12:00:00

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.



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.



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(?). Event queueing and synchronous calls are still a little unclear to me.



Any thoughts on how I can make this work?


More From » jquery

 Answers
7

.each() calls are not 'queued', they just execute the given function on each element of the collection, one after the other. So you set for each button-click a timeout of 200ms. The result: 200ms later all buttons are triggered at (nearly) same time. 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.... .


[#41403] Thursday, November 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;