admin管理员组文章数量:1332345
I have this script:
var array = [];
array[0] = '/';
array[1] = '/';
array[2] = '';
$(document).ready(function()
{
for(i=0; i<= 2; i++)
{
$('#ifr').attr('src', array[i]);
// sleep here for 0,5 second
}
});
And how I can stop this loop for 0.5 second?
I have this script:
var array = [];
array[0] = 'http://facebook./';
array[1] = 'http://instagram./';
array[2] = 'http://twitter.';
$(document).ready(function()
{
for(i=0; i<= 2; i++)
{
$('#ifr').attr('src', array[i]);
// sleep here for 0,5 second
}
});
And how I can stop this loop for 0.5 second?
Share Improve this question asked Apr 5, 2016 at 19:35 MajksonMajkson 2274 silver badges15 bronze badges 4- there is no sleep in javascript.... – I wrestled a bear once. Commented Apr 5, 2016 at 19:38
- @Pamblam So give me an alternative in javascript. – Majkson Commented Apr 5, 2016 at 19:39
- @blex can u give me an example? – Majkson Commented Apr 5, 2016 at 19:40
- 1 @Majkson You've got 2 answers right below and they both work. Choose the one you like. – blex Commented Apr 5, 2016 at 19:46
2 Answers
Reset to default 6You can use setTimeout
for this purpose,
for(i=0; i<=2; i++) {
setTimeout(function(i) {
$('#ifr').attr('src', array[i]);
},500 * i,i);
//1000 ms is 1 sec, here I have give 0.5 seconds as a delay.
}
There is no need to create scope per iteration for handling the closure problem. You can use the third parameter of setTimout
to set the argument of callBack
function.
(function rec(i){
setTimeout(function(){
$('#ifr').attr('src', array[i]);
if(i <= 2) rec(i+1);
}, 5000);
})(0);
EDIT: added if(i <= 2)
so that it doesn't recurse forever.. this will stop it after 2 iterations..
本文标签: Javascriptsleep() in for loopStack Overflow
版权声明:本文标题:Javascript - sleep() in for loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742324884a2453526.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论