Slideshow error "RangeError: Maximum call stack size exceeded - javascript

I am trying to add this image slideshow into my website, However keeping running into a MAximum call stack size exceeded. The slider runs through the images not in the time interval set and then the error occurs
var i = 0; // Start Point
var images = []; // Images Array
var time = 3000; // Time Between Switch
// Image List
images[0] = "http://lorempixel.com/400/200/animals";
images[1] = "http://lorempixel.com/400/200/sports";
images[2] = "http://lorempixel.com/400/200/food";
images[3] = "http://lorempixel.com/400/200/people";
// Change Image
function changeImg(){
document.slide.src = images[i];
// Check If Index Is Under Max
if(i < images.length - 1){
// Add 1 to Index
i++;
} else {
// Reset Back To O
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload=changeImg;

I am posting this as an answer to have a minimal, complete and verifiable example (mcve) to make sure that the slider is not the culpritd, the code will not give that error.
Here is current syntax - if that still gives an error then there is certainly something else wrong
let i = 0, img;
const images = ["https://via.placeholder.com/150/0000FF/808080?text=Image1",
"https://via.placeholder.com/150/FF0000/FFFFFF?text=Image2",
"https://via.placeholder.com/150/FFFF00/000000?text=Image3",
"https://via.placeholder.com/150/000000/FFFFFF/?text=Image4"
];
const changeImg = function() {
slide.src = images[i];
i++;
if (i >= images.length) i = 0;
}
window.addEventListener("load", function() {
img = document.getElementById("slide");
changeImg();
setInterval(changeImg, 2000);
})
<img id="slide" />

Related

I would like to take more than one slideshow from this to one page

I have a code, a simple automatic slideshow. I would like to place more than 1 slideshow, but they will overwrite each other. Please help me how can i solve this. Please help me to solve this problem. I would like to use these slideshows on the same page, but when a i try only 1 slideshow works. I would like to use 8 types of this slideshow in the future. And 1 extra, i would like to place a simple animation between the pics when they switch.
html:
<div class="pic-wrapper">
<img name="slide" width="400" height="377" object-fit="cover"/>
</div>
and
<div class="pic-wrapper">
<img name="slide2" width="400" height="377" object-fit="cover"/>
</div>
and my javascripts:
<script>
var i = 0; // Start Point
var images = []; // Images Array
var time = 3000; // Time Between Switch
// Image List
images[0] = "img/kosar/kosar1.jpg";
images[1] = "img/kosar/kosar2.jpg";
images[2] = "img/kosar/kosar3.jpg";
images[3] = "img/kosar/kosar4.jpg";
// Change Image
function changeImg(){
document.slide2.src = images[i];
// Check If Index Is Under Max
if(i < images.length - 1){
// Add 1 to Index
i++;
} else {
// Reset Back To O
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload=changeImg;
</script>
and
<script>
var i = 0; // Start Point
var images = []; // Images Array
var time = 3000; // Time Between Switch
// Image List
images[0] = "img/roplabda/ropi1.jpg";
images[1] = "img/roplabda/ropi2.jpg";
images[2] = "img/roplabda/ropi3.jpg";
images[3] = "img/roplabda/ropi4.jpg";
// Change Image
function changeImg(){
document.slide.src = images[i];
// Check If Index Is Under Max
if(i < images.length - 1){
// Add 1 to Index
i++;
} else {
// Reset Back To O
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload=changeImg;
</script>
Why don't you merge your script into something like this ?
var slide1 = 0; // First Slide index
var slide2 = 0; //Second Slide Index
var images = []; // Images Array
var time = 3000; // Time Between Switch
// Image List
imageObjects = { 'firstSlide': [
"img/roplabda/ropi1.jpg",
"img/roplabda/ropi2.jpg",
"img/roplabda/ropi3.jpg",
"img/roplabda/ropi4.jpg",
],
'secondSlide': [
"img/kosar/kosar1.jpg",
"img/kosar/kosar2.jpg",
"img/kosar/kosar3.jpg",
"img/kosar/kosar4.jpg"
]};
// Change Image
function changeImg(){
document.slide.src = imageObjects.firstSlide[slide1];
document.slide2.src = imageObjects.secondSlide[slide2];
// Check If Index Is Under Max
if(slide1 < imageObjects.firstSlide.length - 1){
// Add 1 to Index
slide1++;
} else {
// Reset Back To O
slide1 = 0;
}
if(slide2 < imageObjects.secondSlide.length - 1){
// Add 1 to Index
slide2++;
} else {
// Reset Back To O
slide2 = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload=changeImg;
If you really want to keep separate scripts for these slideshow, for whatever reason. Then you should probably keep your variables names of "i" & "images" unique and not repeat them in next script.

Javascript show imgs one by one with interval

I have the below images and I'm trying to show them one by one by interval of 3 seconds, but I am not able to get it work. It continues to stay on 0 and does not show the image, help would be nice:
<img src="one.png"></img>
<img src="two.png"></img>
javascript :
window.animate = function(){
var timer = '';
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var timer = setInterval(function(){
alert(i);
imgs[i].style.display = 'block';
}, 3000);
if(i == imgs.length){
clearInterval(timer);
}
}
}
This might be what you're looking for:
window.animate = function(){
var imgs = document.getElementsByTagName('img');
var index = 0;
var timer = setInterval(function() {
// Hide all imgs
for (var i = 0; i < imgs.length; i++)
imgs[i].style.display = 'none';
// Display next img
imgs[index].style.display = 'block';
index++;
// Stop after all displayed.
if (index >= imgs.length)
clearInterval(timer);
}, 3000);
}
Here is one way to do it:
Fiddle: http://jsfiddle.net/aecuappp/
HTML:
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
JS:
var imgs = document.getElementsByTagName('img');
var interval = 3000;
for (var i = 0; i < imgs.length; i++) {
(function (index, time) {
setTimeout(function() {
imgs[index].style.display = 'block';
}, time);
} (i, interval));
interval = interval + 3000;
}
CSS:
img {
display: none;
}
Basically you can start interval at 0 if you want first image to show up immediately. And each time it adds 3 seconds to the timeout since these are all created roughly at the same time. I wrapped the setTimeout in an IIFE to give interval and index scope for when the timeout needs the values at the time we created the timeout.
Since these are essentially all timing out at the same time, you need to implement a callback pattern to your interval to trigger the next one, or you need to increase the interval per index; i.e. set the timer's interval to 3000*(i+1), which will effectively trigger the next one at the delay plus the previous delay. This does not account for the actual images load however. Additionally, I would consider using setTimeout since you only need to do this once.
var img = $('img.targets');
for (var i=0;i<img.length;i++) {
var duration = 3000;
setTimeout( function() {
// do dom work here
}, duration*(i+1));
}
You can accomplish this by queuing up some timeouts using setTimeout and then making sure you are correctly passing the value of i to the function within. You can do that easily by using forEach instead of a regular loop:
window.animate = function() {
var imgs = document.getElementsByTagName('img');
imgs.forEach(function(img, i) {
setTimeout(function() {
img.style.display = 'block';
}, (i + 1) * 3000);
});
};

Javascript - loading images

I have a javascript which uses many images, and I want to load them all before the user starts clicking around. The images are a little bit big, so it takes a while. Here's my code:
startTest();
function preloadImages() {
console.log("preload images");
for(var i = 1; i <= 132; i++) {
var img = new Image();
images[i-1] = "images/"+i+".png";
img.src = images[i-1];
if(i == 132) {
img.load = doneLoading();
}
}
}
function doneLoading() {
console.log("done loading");
document.getElementById("laading").style.display = "none";
console.log("loading gone");
showReady();
}
function startTest() {
console.log("start test");
trialCount = 0;
document.getElementById("laading").style.display = "block";
preloadImages();
var hammertime = Hammer(document.body).on("touch", function(event) {
registerTouch(event);
});
startTestTime = +new Date();
console.log("end start test");
}
As you can see, startTest() is first called, which calls preload images. Here's the issue:
When I load the page in the browser, the javascript console indicates that "done loading" has been printed, however the spinny wheel on the tab in the browser shows that the webpage is still loading...
What's going on here? How can I figure out once all my images are done loading?
You need to check on each image load that the image is the last one to load. Check using a count variable (loaded).
function preloadImages() {
var loaded = 0;
for(var i = 0; i <= 132; i++) {
var img = new Image();
images.push("images/"+(i+1)+".png");
img.src = images[i];
img.onload = function(){
loaded++;
if(!(loaded < 132)){
// all images have loaded
doneLoading();
}
}
}
}
In order to do a pre-loading, you will have to keep checking the complete status for each image that is being downloaded. Since, you can't know beforehand how much time it will take for each image to download (depending on latency or size), you will have to implement a timer which will keep polling the complete status on each image.
Here is one possible algorithm:
var timer = null,
numImages = 132,
allImages = new Array;
function preLoadImages() {
document.getElementById('loadcaption').innerHTML = 'Loading images... ';
for (var i = 0; i < numImages; i++) {
var tmp = "images/" + i + ".png";
allImages[i] = new Image();
allImages[i].onLoad = imgOnLoad(tmp);
allImages[i].src = tmp;
}
timer = window.setInterval('checkLoadComplete()', 250);
}
function imgOnLoad(imgName) { window.status = 'Loading image... ' + imgName; }
function checkLoadComplete() {
for (var i = 0; i < allImages.length; i++) {
if (!allImages[i].complete) {
imgOnLoad(allImages[i].src);
document.getElementById('loadcaption').innerHTML = 'Loading images... ' + Math.round((i/allImages.length)*100,0) + ' %';
return;
}
}
window.clearInterval(timer);
document.getElementById('loadcaption').innerHTML = 'Completed.';
window.status = '';
}
Where loadcaption is a simple HTML element to show progress. (You can also use an animated gif for loading animation).
The idea is to keep checking the complete status on each image by calling checkLoadComplete by a timer. Once all images are (load) complete, the for loop exits and the timer is cleared.
You start the pre-loading process by calling preLoadImages(); function.

Redirect after loading images

So I have been recently developing a site, The problem is the backgrounds for each page are images, and as a result, on slower connections (which is the case of some of the target audience) the images load progressivly as they are downloaded, to resolve this I am trying to make a preloading page that does the following :
Loads the Images
Once the loading is done, redirects the user to the requested page
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
var count=0;
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
if(count==4) {
window.location = "index.html";
}
}
preload(
"backgrounds/bg1.jpg",
"backgrounds/bg2.jpg",
"backgrounds/bg3.jpg",
"backgrounds/bg4.jpg"
)
//--><!]]>
The problem is it redirects directly (I assume that it just starts the download of the image then directly adds one to the counter variable, quickly reaching 4 and not giving the image the time to download.
Any ideas how I can either make it signal me when the images have finished downloading, or only execute the redirect after it has done downloading the images ?
You need to wait for the load event. It's quite simple:
function preload(images, timeout, cb) {
var cbFired = false,
remaining = images.length,
timer = null;
function imageDone() {
remaining--;
if(remaining === 0 && !cbFired) {
cbFired = true;
clearTimeout(timer);
cb();
}
}
function timerExpired() {
if(cbFired)
return;
cbFired = true;
cb();
}
for(var i = 0; i < images.length; i++) {
var img = new Image();
img.onload = imageDone;
img.onerror = imageDone;
img.src = images[i];
}
timer = setTimeout(timerExpired, timeout);
}
You need to check a few things so that users don't get stuck:
You need to wait for both load and error so that the page doesn't get stuck if an image fails to load.
You should set a maximum timeout.
Also, in your code, i was a global variable (no var declaration).
Here's how to use it:
var images = [ "backgrounds/bg1.jpg",
"backgrounds/bg2.jpg",
"backgrounds/bg3.jpg",
"backgrounds/bg4.jpg"];
preload(images, 10000 /* 10s */, function () {
window.location = 'next_page';
});
Modify your preloader so that it binds to the "onload" event of the Image object and when all callbacks are fired it redirects (untested sample code below):
var images = new Array()
var count = 0;
function preload() {
var numImages = preload.arguments.length
for (i = 0; i < numImages; i++) {
images[i] = new Image();
images[i].onload = doneLoading; // See function below.
images[i].src = preload.arguments[i];
}
function doneLoading() {
if (++count >= numImages) {
window.location = "index.html";
}
}
}
preload(
"backgrounds/bg1.jpg",
"backgrounds/bg2.jpg",
"backgrounds/bg3.jpg",
"backgrounds/bg4.jpg"
)

use of "setTimeout" to repeat function causes browser to display "Loading..." message

I have this banner rotator which is working fine except for one problem...
This rotator here first goes through the function and when it reaches the "setTimeout" statement it triggers the "cycle" function again and again.
You guys probably know that in Firefox there is a status-bar in the bottom-left corner, which says "loading" or "waiting for domain.com..." etc etc.
The problem is this; When you enter the website in Firefox, the status bar says "Loaded" and dissappears. Then after 8 seconds (the setTimeout delay) the status bar shows again and displays something like "Getting data from domain.com...". And it doesn't go away.
This message is most likely caused by the setTimeout code, which triggers the function cycle over and over again.
Is there any way of "solving" this?
This probably happens in other browsers also, but so far I have only tested it in FF.
function ban_rot(){
//First preload images
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0] = "../Graphics/adv/1.gif"
images[1] = "../Graphics/adv/2.jpg"
// start preloading
for (i = 0; i <= images.length; i++) {
imageObj.src = images[i];
}
///////////////////////
var links = new Array("http://www.link1.com", "http://www.link2.se");
var alts = new Array("alt1", "alt2");
var titles = new Array("title1", "title2");
var counter = 0;
var banner_div = document.getElementById("ban_rot");
cycle();
function cycle() {
if (counter == links.length) {
counter = 0;
}
else if (counter < links.length) {
banner_div.innerHTML = '<img src=\"' + images[counter] + '\" border=\"1px\" style=\"border-color:#000;\" alt=\"' + alts[counter] + '\" title=\"' + titles[counter] + '\">';
//increase counter
counter++;
}
setTimeout(cycle, 8000);
} //end cycle function
} //end ban_rot function
The browser is showing a loading indicator because you're making it load a new image.

Categories

Resources