简体   繁体   中英

js, jquery - settimeout and for loop

I would like to do following instructions:

1. Fill input with id "ivoucher".
2. Click button with class "voucher-add-check".
3. Wait 5 seconds

And i would like to have it in for loop. I have following code, but it not working:

(function() {
'use strict';

for (var i = 1; i <= 3; i++) {
    (function(a) {
        jQuery('#ivoucher').val(i);
        $('button[class*="voucher-add-check"]').click();
        setTimeout(function() {
            console.log(document.getElementById('ivouchermessage'));
        }, i * 5000);
    })(i);
}
})();

It seems you want the delay to happen before the next value is assigned. In that case you need an asynchronous loop. One way to do that is to call a function from within the setTimeout callback:

(function loop(i) {
    if (i > 3) return; // all done
    $('#ivoucher').val(i);
    $('button[class*="voucher-add-check"]').click();
    setTimeout(function() {
        loop(i+1); // only now continue the "loop"
    }, 5000);
})(1); // start value of i

Note that in your code:

  • you called the argument a , which you did not use.
  • all three assignments and clicks happened immediately (not subject to the timeout)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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