Loop function to run 25 times but at 2 second interval - javascript

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);

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

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

Issue linking images to dynamically created jquery elements

So, I'm very new, so apologies if this is a silly question. I have worked out a Trivia Quiz for my learning to code classes I'm taking. I want to display an image on the confirmation screen that shows whether the user was right or wrong. I think the code is correct-ish? I'm not sure what isn't working.
I left out the main Question and answer object for space. Sorry if I didn't format this ideally? I'm still kinda figuring out how things work here.
Here is my code for reference:
//array to help me iterate and insert images
var imgArray = ["question1", "question2", "question3", "question4", "question5", "question6", "question7", "question8", "question9", "question10", "question11", "question12", "question13"];
var currentQuestion = 0;
var win = 0;
var lose = 0;
var unanswered = 0;
var time = 30;
//set up divs to contain our info
var rightDiv = $("<div class='rightAns'></div>");
var timerDiv = $("<div class='countdown'><h3></h3></div>");
var questionDiv = $("<div class='question'><h1></h1></div><br>");
var answerDiv = $("<div class='answers'></div>");
//object keys to return questions in order
var keys = Object.keys(questions);
var key = keys[n];
var n = 0;
//function to setup and restart game
function reset() {
$("#start-button").hide("slow");
$("#start-here").hide("slow");
win = 0;
lose = 0;
unanswered = 0;
n = 0;
key = keys[n];
currentQuestion = 0;
$("#question-block").empty();
var reset = function () {
time = 30;
$(".rightAns").empty();
$(".rightAns").remove();
// $("#image").empty();
$("#time-remaining").append(timerDiv);
$(".countdown h3").html("Time Remaining: " + time);
$("#question-block").append(questionDiv);
$("#question-block").append(answerDiv);
}
reset();
//function to show questions
function showQuestion() {
$(".question h1").html(questions[key].question);
for (var i = 0; i < questions[key].answers.length; i++) {
$(".answers").append("<button class='answer btn btn-danger btn-lg m-1'>" + questions[key].answers[i] + "</button>");
}
$(".answers button").on("click", function () {
var selected = $(this).text();
//if then to check question correctness
if (selected === questions[key].correct) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("That's Correct!!");
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
win++;
currentQuestion++;
} else {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("Nope! The correct answer was: " + questions[key].correct);
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
lose++;
currentQuestion++;
}
n++;
key = keys[n];
//checking to see if there are more questions left
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
});
}
showQuestion();
var counter = setInterval(count, 1000);
//show time remaining for each question
function count() {
time--;
$(".countdown h3").html("Time Remaining: " + time);
if (time < 1) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").html("You took too long! The correct answer was: " + questions[key].correct);
unanswered++;
n++;
key = keys[n];
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
}
}
function checkForLast() {
if (key === undefined) {
return true;
}
return false;
}
//timer for the message after you choose your answer
function countReset() {
counter = setInterval(count, 1000);
}
//showthe final score screen
function finalScore() {
$(".rightAns").remove();
$("#image").empty();
$("#question-block").prepend("<h2>Unanswered: " + unanswered + "</h2>");
$("#question-block").prepend("<h2>Incorrect: " + lose + "</h2>");
$("#question-block").prepend("<h2>Correct: " + win + "</h2>");
$("#start-button").show();
$("#start-here").show();
}
};
//function to start game on button click
$(document).on("click", "#start-button", reset);
});
After tinkering for a bit, I dropped the "." at the beginning of the call and added the .jpg to the section after imgArray[currentQuestion]. That solved it. Thanks for the suggestions.

Image Slideshow in js hanging app

I have written this method in javascript:
function displayImage() {
window.setInterval(function(){
for (var i = 1; i <= 4; i++) {
document.getElementById("img1").setAttribute("src",
"images/th-" + i + ".jpg");
if(i==4){
i=0;
}
}
}, 3000);
}
and am calling this method from html page: . But after 3 sec, my application hangs and nothing happens. What is going wrong in this?
In this case your for loop will work 4 times after every 3000 milliseconds. You need to change one picture after each 3000 milliseconds.
Try this
function displayImage() {
var img = document.getElementById("img1");
var imgIndex = 1;
window.setInterval(function(){
img.setAttribute("src", "images/th-" + imgIndex + ".jpg");
imgIndex = imgIndex === 3 ? 0 : imgIndex + 1;
}, 3000);
}

Executing setTimeout() in loop takes effect only in the first iteration [duplicate]

I'm trying to make a few things scroll down the screen in javascript, however, upon execution, it just says a little and displays everything at once. So it's not clearing with the $("#Menu").html('') function and the setTimeout(function {},500) is just setting a timeout for the entire page instead of the code segment.
var MenuData = [
{'Name':'pictures','x':'30'},
{'Name':'blog','x':'50'},
{'Name':'contact','x':'42'}
]
;
var PositionArray = new Array();
$(document).ready(function () {
for (var count = 0; count < 1000; count++) {
$("#Menu").html('');
if (PositionArray[count] != null) {
PositionArray[count]++;
} else {
PositionArray[count] = 0;
}
setTimeout(function () {
for (var i in MenuData) {
$("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
}
}, 500);
}
});
Here's the fiddle: http://jsfiddle.net/LbjUP/
Edit: There was a little bit of error in the code that doesn't apply to the question. Here's the new one: http://jsfiddle.net/LbjUP/1/, I just moved PositionArray[count] to the setTimeout function as PositionArray[i]
As stated in the comments, you are creating 1000 timeouts for 500 ms at the same time - after 500 ms all of them will be executed. What you want is to increase the timeout for every scheduled function:
setTimeout(function() {
// do something
}, count * 500);
However, creating 1000 timeouts at once is not a that good idea. It would be better to use setInterval or call setTimeout "recursively" until a count of 1000 is reached, so that you only have one active timeout at a time.
var count = 0;
function update() {
// do something
if (++count < 1000)
setTimeout(update, 500);
// else everything is done
}
update();
Also, if you intend to create timeouts in a loop, be sure to be familiar with closures and their behavior when accessing counter variables after the loop ran.
Try
function recurse ( cnt ) {
for (var i in MenuData) {
$("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
}
if (cnt < 1000){
setTimeout(function () { recurse(cnt + 1); }, 500);
}
}
$("#Menu").html('');
if (PositionArray[count] != null) {
PositionArray[count]++;
} else {
PositionArray[count] = 0;
}
recurse(0);
You can also use setInterval
let i = 0;
const interval = setInterval(() => {
console.log(i);
i++;
if (i >= 10) {
clearInterval(interval);
}
}, 1000);`

only the last setInterval run

I have the following javascript code
function RefreshElastic() {
Elastic.refresh();
}
function ShowTime() {
var Sekarang = new Date();
var Waktu = Sekarang.getDate() + "/" +
Sekarang.getMonth() + " - " +
Sekarang.getHours() + ":" +
Sekarang.getMinutes();
$("#jam").html(Waktu);
Elastic.refresh();
}
var IntervalElastic = setInterval(function () {
RefreshElastic();
}, 500);
var IntervalTime = setInterval(function () {
ShowTime();
}, 1000 * 30);
I want to have 2 intervals, each has a function to call.
The RefreshElastic called only twice.
The ShowTime always called every 30 seconds.
Why is that?
Additional note:
I changed the millis for RefreshElastic to a larger value, like 5000. And RefreshElastic never called.

SetInterval not refreshing HTML in Chrome

I'm trying to implement a script that essentially counts down from 30 seconds to 0, and at 0, redirects to the homepage. However, I noticed that my script only works on Firefox but not Chrome and Safari. On these browsers, the counter remains "stuck" at 30 seconds—never refreshing the HTML, but the redirect works fine. Not sure if I'm doing something wrong or if setInterval is not the right method for this kind of thing.
<script>
var seconds = 31;
var counter = setInterval("timer()", 1000);
function timer() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>
Thanks in advance!
EDIT: So weirdly enough, my code (and all of yours) is working on JSFiddle, but it's just failing to "repaint" the HTMLinner when it's actually rendering the page. The seconds are changing fine (I outputted them to the console), the changes just aren't rendering.
Final Edit: This problem basically resulted from invalid CSS. I believe—the counter was running above the photo and I set the span to relative positioning with a higher z-index and top and bottom elements. I don't believe this is acceptable for something that is not a block.
Here's a working sample:
(function() { // wrapper for locals
var timer = document.getElementById("timer"),
seconds = 5,
counter = setInterval(function() {
if (--seconds < 1) {
clearInterval(counter);
timer.innerHTML = "Redirecting now...";
setTimeout(function() {
location.href = 'http://www.homepage.com';
}, 500);
} else {
timer.innerHTML = timer.innerHTML.replace(/\d+/, seconds);
}
}, 1000);
})();
<div id="timer">Redirecting in 5 seconds</div>
​
​
Here is a cleaner implementation with fewer defined functions (with demo):
<span id='timer'></span>
<script>
var seconds = 31;
setInterval(function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout(function() {document.getElementById('timer').innerHTML = "redirecting..."}, 100);
return;
}
updateTimer();
}, 1000);
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + + seconds + " seconds";
}
<script>
Of course every JavaScript programmer should any opportunity to point out that "eval is evil" which includes passing a string to setInterval and setTimeout :)
Change your function to a variable, that worked for me:
<script>
var seconds = 31;
var counter = setInterval(timer, 1000);
var timer = function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>

Categories

Resources