Javascript recursion setup

I just started looking at javascript, so hopefully this will be something simple. I want to make a slide show of images that play automatically. It is very simple, and there are several tutorials, but for some reason I could not get it to work. This is what I have:

var image1 = new Image(); var image2 = new Image(); var image3 = new Image(); image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg"; var images = new Array( "images/website6.jpg", "images/website7.jpg", "images/sunset.jpg" ); setTimeout("delay(images,0)",2000); function delay(arr,num){ document.slide.src = arr[num % 3]; var number = num + 1; setTimeout("delay(arr,number)",1000); } 

The image I'm trying to change has a slide slide. And I also have some evidence that this works. What happens is the first image download. Then the second image is loaded (which means that the original setTimeout call should work). Then nothing happens. Which offers me a recursion that doesn't work.

I am very familiar with recursion in other languages, so I think that this is just a syntactic thing or something like that, but I can not understand it. Thanks for any help.

+7
source share
2 answers

The problem is that when you pass the strings that should be evaluated by calling "setTimeout", the evaluation will be performed (later, when there is time to start) in the global context. This way you are much better (for many other reasons) passing in real functions:

 setTimeout(function() { delay(images, 0); }, 2000); function delay(arr, num) { document.slide.src = arr[num % 3]; setTimeout(function() { delay(arr, num + 1); }, 1000); } 

In more modern browsers, you can use the ".bind ()" method to create functions that are pre-bound to something that will be used like this :

 setTimeout(delay.bind({arr: images, num: 0}), 2000); function delay() { document.slide.src = this.arr[this.num % 3]; setTimeout(delay.bind({arr: this.arr, num: this.num + 1}), 1000); } 

Six out of one, half a dozen another, but as an example that shows that there are several ways to do something.

+15
source

I would be very suspicious of the second call to setTimeout . I would clarify using an explicit function against a string expression

 setTimeout(function() { delay(arr, number); }, 1000); 
+1
source

All Articles