简体   繁体   中英

Calling Function Inside the Function itself

Can anyone explain why did we call the function inside the function rather than calling it outside?

 let i = 0; let images = []; const time = 500; images[0] = 'Images/carousel1.jpg'; images[1] = 'Images/carousel2.jpg'; images[2] = 'Images/carousel3.jpg'; const changeImg = () => { document.slide.src = images[i]; if(i < images.length - 1) { i++; } else { i = 0; } setTimeout('changeImg()', time); }; onload = changeImg;
 <img src="" name="slide">

If, your question, is why do we call setTimeout('changeImg()', time); from inside the changeImg function, well let's take a look.

When the onload event triggers, changeImg will be called, kicking things off. Which will swap out images, based on the value of i . Each time changeImg is called it schedules the next call of changeImg for time seconds in the future.

This has a couple features to how it's currently implemented which may be interesting...

First we could have used setInterval to call the changeImg function, from outside of the function, but depending on the timings involved could lead to off time swapping of the images.

As these setInterval/setTimeout functions do not guarantee when they will fire, just that they will sometime after their set timeouts, so it's possible one or more such calls could trigger next to each other, messing with the timings...

By using the nested setTimeout, you guarantee only one such event is pending at any given time, and only after the work has been done, the next event gets scheduled.

So we can see that by nesting the call, we get a guaranteed order and min span of time between calls/images swaps.

You can play with this playground , to see how the timings can get out of sync... just play with the slider control a bit and you will see the slides go out of sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM