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

本文标签: Javascriptsleep() in for loopStack Overflow