循环睡眠的Jquery

时间:2016-04-14 14:52:02

标签: jquery

如何在.create_reservation上的点击功能之间进行循环睡眠?现在他们都在.create_reservation120

同时点击了
$( "#button-1" ).click(function() {
    if (confirm('Are you sure ?')) {
        var order_s = 20;
        var i;
        for (i = 0; i < order_s; i++) {
            $(".create_reservation" + i).click();
        }
    }
});

1 个答案:

答案 0 :(得分:4)

您可以通过使用setTimeout()函数创建一个接受回调的函数(即您想要执行的操作)和要在集合中的每个项目之间应用的延迟来完成此操作:

// callback is the function you want to execute and timeout is the
// delay in milliseconds between each
function clickTheButtons(callback, timeout) {
    // Store the buttons you need to click (every element that starts 
    // with .create_reservation)
    var buttons = $('[class^="create_reservation"]');
    // Store the current button you are on (so you know when to stop)
    var currentButton = 0;
    // Create a callback loop that will click each button
    // and wait until the next one
    (function processNextButton() {
        // Trigger your callback to process this current item
        callback.call(buttons[currentButton++]);
        // As long as there is one to process, do so
        if (currentButton < buttons.length) {
            // Indicate that you want to click the next button after the timeout
            // has elapsed
            setTimeout(processNextButton, timeout);
        }
    }());
}

然后通过以下方式调用此方法:

if(confirm('Are you sure?'){
     // Start clicking the buttons (1 second delay between each)
     clickTheButtons(function() { $(this).click();},1000);
}

您可以see an interactive example here并在下面进行演示:

enter image description here