0

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);
}
})();
2
  • "Not working" means what, exactly? What does it do that you don't want? What doesn't it do that you do what? Commented Nov 5, 2017 at 22:08
  • Var i is defined in the loop. Inside your IIFE you should use a (parameter of the function). Commented Nov 5, 2017 at 22:17

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Could you leave a comment on whether this suited your needs?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.