如何用jQuery将触发元素点击的定时代码改为无限循环执行?
Solution to Convert One-Time Timeouts to Infinite Loop with jQuery
Got it, let's get this sorted for you! You're currently using one-off setTimeout calls to trigger clicks at specific intervals, and you want to turn this into an infinite repeating sequence using only jQuery for element interactions.
Here's the modified code that runs your click sequence on loop:
// Define the function that runs your click sequence function repeatClickSequence() { // First click on #click2 after 4 seconds setTimeout(function() { $('#click2').trigger('click'); // Second click on #click2 after another 4 seconds (total 8s from start) setTimeout(function() { $('#click2').trigger('click'); // Click on #click3 after another 4 seconds (total 12s from start) // Then restart the sequence to create an infinite loop setTimeout(function() { $('#click3').trigger('click'); repeatClickSequence(); // Recursively call the function to repeat the cycle }, 4000); }, 4000); }, 4000); } // Start the infinite loop repeatClickSequence();
How this works:
- We wrap your original timeout sequence into a reusable function
repeatClickSequence. - After the final click on
#click3, we recursively call the same function to start the entire sequence over again—this creates the infinite loop. - All element selections and click triggers use jQuery (
$('#click2').trigger('click')), which aligns with your requirement to stick to jQuery for element interactions.
Optional: Add a way to stop the loop
If you ever need to pause or stop the infinite loop, you can add a boolean flag to control execution:
let keepLooping = true; function repeatClickSequence() { // Exit the function if we've stopped the loop if (!keepLooping) return; setTimeout(function() { $('#click2').trigger('click'); setTimeout(function() { $('#click2').trigger('click'); setTimeout(function() { $('#click3').trigger('click'); repeatClickSequence(); }, 4000); }, 4000); }, 4000); } // Start the loop repeatClickSequence(); // To stop the loop later, run this line: // keepLooping = false;
This gives you full control over starting and stopping the automated click sequence whenever you need.
内容的提问来源于stack exchange,提问作者rawand feryad
相关产品推荐
相关产品推荐

