Reputation: 13
I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning.
Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?
Upvotes: 1
Views: 5605
Reputation: 340316
You should use a timer to continuously bring new images instead of an infinite loop. Check the setTimeout()
function. The caveat is that you should call it in a function that calls itself, for it to wait again. Example taken from w3schools:
var c = 0
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout("timedCount()", 1000);
}
<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
</form>
Upvotes: 3
Reputation: 4105
Try setInterval or setTimeout.
Here is an example:
(show = (o) => setTimeout(() => {
console.log(o)
show(++o)
}, 1000))(1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 8
Reputation: 90
function foo() {
alert('hi');
setTimeout(foo, 5000);
}
Then just use an action like "onload" to kick off 'foo'
Upvotes: 0
Reputation: 3251
Just a formal answer:
var i = 0;
while (i < 1) {
do something...
if (i < 1) i = 0;
else i = fooling_function(i); // must return 0
}
I think no browser would detect such things.
Upvotes: 0
Reputation:
If it fits your case, you can keep loading new images to respond to user interaction, like this website does (just scroll down).
Upvotes: 0
Reputation: 58959
The following code will set an interval and set the image to the next image from an array of image sources every second.
function setImage(){
var Static = arguments.callee;
Static.currentImage = (Static.currentImage || 0);
var elm = document.getElementById("imageContainer");
elm.src = imageArray[Static.currentImage++];
}
imageInterval = setInterval(setImage, 1000);
Upvotes: 2
Reputation: 74682
Instead of using an infinite loop, make a timer that keeps firing every n seconds - you'll get the 'run forever' aspect without the browser hang.
Upvotes: 1
Reputation: 4012
Perhaps try using a timer which retrieves the next image each time it ticks, unfortunately i don't know any JavaScript so I can't provide a code sample
Upvotes: 0