0

I'm using jquery load() to load some files.

I need to have a 1 second gap each time the myfuc() is called inside this load() function.

This is what I did. Currently it doesn't call myfuc() every 1 second, it calls myfuc() 9 times at the same time.

My requirement is to call myfuc() when each html file if fully loaded. or To call myfuc() with a 1 second gap

for(i = 1; i < 10; i++){
   $('#wrapper' + i ).load('some'+i+'.html', function(index) {
      setTimeout(function() {
         myfuc();
      }, 1000 * (index + 1));
   });
}
Becky
  • 5,467
  • 9
  • 40
  • 73

3 Answers3

0

setInterval(myFunc, 1000);

Try this!

Sampaio Leal
  • 125
  • 1
  • 7
0
// Select all images and for each
$('[id^="wrapper"]').each(function(idx) {
    // ... register listening on load event...
    var i = idx + 1;
    $(this).load('some'+i+'.html', function() {
        // ...and if particular image is loaded, start timer...
        setTimeout(function() {
        // ...which fires this func
            myfuc();
       }, 1000 * i);
    });
});

If you explicitly need read var i from tag id

function myFunc(i) {
  console.log("Image with id wrapper"+i+" loaded"); 
}

$('[id^="wrapper"]').each( function() {  
  var i = parseInt($(this).prop("id").substring(7),10) ; 
  $(this).load('some'+i+'.html', function() {    
    setTimeout(function() {
      myFunc(i);
    }, 1000 * i);    
  });  
});
<img src="http://placehold.it/100/60?text=Image 1" id="wrapper1">
<img src="http://placehold.it/100/60?text=Image 2" id="wrapper2">
<img src="http://placehold.it/100/60?text=Image 3" id="wrapper3">
<img src="http://placehold.it/100/60?text=Image 4" id="wrapper4">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
-1

it can be a scope problem - the set timeout gets the same i every time.

you can try solving it with the let variable

   for(let i = 1; i < 10; i++){
       $('#wrapper' + i ).load('some'+i+'.html', function(i) {
           setTimeout(function() {
               myfuc();
           }, 1000 * (i+ 1));
       });
   }

or with an IIFE

   for(var i = 1; i < 10; i++){
       (function (index) {
           $('#wrapper' + index).load('some'+index+'.html', function(index) {
               setTimeout(function() {
                   myfuc();
               }, 1000 * (index+ 1));
           });
       })(i);
   }
naortor
  • 2,019
  • 12
  • 26
  • 1
    Thanks. Why use `i` inside `function(i)` ? – Becky Sep 07 '16 at 11:00
  • I edited it to make it more clear, in order to keep the right value of variable i i'm passing it as a value to the self invoked function. [you can read more about it here](http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript) – naortor Sep 07 '16 at 11:06