Home > Software engineering >  Loop function to run 25 times but at 2 second interval
Loop function to run 25 times but at 2 second interval

Time:08-08

I have the following function to open an iframe , i need to run this function 25 times and open 25 iframes with different url parameter paths.

After the function is ran , i will get some content , then close the iframe , then reopen a new iframe using a url with the next parameter of "SEQNO=100" , to 101 , 102 etc all the way to 124.

How can i get this to work , i tried setting a loop but it opened all frames at same time

function backupMSG() {

    // OPEN NEW IFRAME EACH TIME FUNCTION RUNS - ITERATE "SEQNO=100 to SEQNO 125"
    $('body').append("<iframe src='"   baseURLDynamic   "/"   year   "/csetup?L="   league_id   "&C=HMPGMSG&SEQNO=100&PRINTER=1' id='iframe'></iframe>");
    $('body').append("<iframe src='"   baseURLDynamic   "/"   year   "/csetup?L="   league_id   "&C=HMPGMSG&SEQNO=101&PRINTER=1' id='iframe'></iframe>");
    $('body').append("<iframe src='"   baseURLDynamic   "/"   year   "/csetup?L="   league_id   "&C=HMPGMSG&SEQNO=102&PRINTER=1' id='iframe'></iframe>");
    // posted 3 urls for example - need to loop over 25 different parameters

    $("#iframe").on("load", function () {
        // Get some content from iframe
        setTimeout(function () {
            console.log("Ran 1 Time") // COUNT HOW MANY TIMES HAS THIS FUNCTION RAN
            $("#iframe").remove();
        }, 600);
        setTimeout(function () {
            backupMSG(); //RUN FUNCTION 25 TIMES AT INTERVAL OF 2 SECONDS
        }, 2000);
    });

}

I tried loops like below but both result in console log of all 25 at same time and i want a delay before it loops through the function again

n=25;
for (let i = 0; i < n; i  ) {
    setTimeout(function () {
        console.log("Hi!" i)
    }, 2000);
}

n=25;
setTimeout(function () {
    for (let i = 0; i < n; i  ) {
        console.log("Hi!" i)
    }
}, 2000);

CodePudding user response:

var i=1,n=25;
setInterval(function(){
    if(i<=n){
        console.log(i);
        i  ;
    }else{
        clearInterval();
    }
},2000)

CodePudding user response:

function backupMSG(id) {
  $("body").append(
    "<iframe src='https://picsum.photos/id/"  
      id  
      "/200/300' id='iframe'></iframe>"
  );

  $("#iframe").on("load", function () {
    setTimeout(function () {
      console.log("Run "   id   " Time");
      $("#iframe").remove();
    }, 600);
  });
}

let startId = 1;
let count = 3;
let interval = setInterval(() => {
  if (startId >= count) clearInterval(interval)
  backupMSG(startId);
  startId  ;
}, 3000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related