You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:28:35