I want to display a certain amount of duplicates for 2 seperate images. The web page prompts the user for the speed, which i have done, and for how many duplicates of each image they want.
function show_image() {
var img = document.createElement("img");
var img2 = document.createElement("img");
img.src = "map.png";
img2.src = "figure-front.png";
document.body.appendChild(img);
document.body.appendChild(img2);
setTimeout("show_image()", speed);
max = 0;
max++
if (max = count) {
return;
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Slide Show</title>
<script src="ShowImages3.js"></script>
<script>
var speed = prompt("Type how fast you want to duplicate", " ");
var count = prompt("Type how many image of each you want to duplicate", " ");
</script>
</head>
<body onLoad="show_image()">
</body>
</html>
However as you can see it runs infinitely apparently
You needed to move the setTimeout and use ==
or ===
for comparison. =
is assignment
It is not recommended to use body onload for anything. Instead use an eventListener.
Here is a cleaner version using setInterval. Also I use >= for the test
And I assign an empty string to the speed and prompt values so I can test using if (speed && prompt) after converting to number using the unary plus. I did not add testing for other than numbers and empty string by the way.
let count = 0, cnt = 0, tId;
const show_image = () => {
if (cnt >= count) {
clearInterval(tId); // stop
return;
}
const img = document.createElement("img");
const img2 = document.createElement("img");
img.src = "map.png";
img2.src = "figure-front.png";
document.body.appendChild(img);
document.body.appendChild(img2);
cnt++; // next
};
window.addEventListener("DOMContentLoaded", () => {
let speed = +prompt("Type how fast you want to duplicate", "");
count = +prompt("Type how many image of each you want to duplicate", "");
if (speed && prompt) tId = setInterval(show_image, speed)
});
Or have this which encapsulates the variables
const generate = (count, speed) => {
let cnt = 0;
let tId;
const addImages = () => {
if (cnt >= count) {
clearInterval(tId); // stop
return;
}
const img = document.createElement("img");
const img2 = document.createElement("img");
img.src = "map.png";
img2.src = "figure-front.png";
document.body.appendChild(img);
document.body.appendChild(img2);
cnt++; // next
};
tId = setInterval(addImages, speed);
};
window.addEventListener("DOMContentLoaded", () => {
let speed = +prompt("Type how fast you want to duplicate", "");
let count = +prompt("Type how many image of each you want to duplicate", "");
if (speed && count) {
generate(count, speed);
}
});