[英]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. 我想将其放入for循环中。 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: 一种方法是从
setTimeout
回调中调用一个函数:
(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: 请注意,在您的代码中:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.