最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - sleep() in for loop - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

You 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..

发布评论

评论列表(0)

  1. 暂无评论