简体   繁体   中英

javascript setTimeout fuction,is something wrong with it

i use settimeout function, why it is not working. i just want to change the image after every 2 seconds. but nothing is happenting it is showing only first image but it is not changing.

<script type="text/javascript">

        function parta(){
            document.getElementById("carimg").src="c1.img";
            window.setTimeout(partb,2000);
        }
        function partb(){
            document.getElementById("carimg").src="c2.jpg";
            window.setTimeout(partc,2000);
        }
        function partc(){
            document.getElementById("carimg").src="c3.jpg";
            window.setTimeout(parta,2000);
        }


</script>

You're declaring three functions over and over and never calling any of them.

If you want to toggle between three images, put them in an array and go through the array one element at a time using setInterval :

var images = ['c1.img', 'c2.jpg', 'c3.jpg'];
var imgNum = 0;

function rotateImage() {
    document.getElementById("carimg").src= images[imgNum];
    imgNum = (imgNum + 1) % images.length;
}

rotateImage();
setInterval(rotateImage, 2000);

If you want to keep your code close to what you have right now, you only need to change a few things:

function parta() {
  document.getElementById("carimg").src="c1.img";
  window.setTimeout(partb,2000);
}
function partb() {
  document.getElementById("carimg").src="c2.jpg";
  window.setTimeout(partc,2000);
}
function partc() {
  document.getElementById("carimg").src="c3.jpg";
  window.setTimeout(parta,2000);
}

parta();

Using while is not necessary in this case, since each function will call each other after 2 seconds. However, you still need to get that "loop" started, which is why you need to call parta() . Also, it might make more sense to use setInterval in this case.

You can play with this code snippet on CodePen: https://codepen.io/yvesgurcan/pen/RwwOawO .

First of all, you don't need to use while and secondly, you missed parentheses of the functions.

 function parta(){ document.getElementById("carimg").src="c1.jpg"; window.setTimeout(partb,2000); } function partb(){ document.getElementById("carimg").src="c2.jpg"; window.setTimeout(partc,2000); } function partc(){ document.getElementById("carimg").src="c3.jpg"; window.setTimeout(parta,2000); } parta();
 <img src="" id="carimg">

Try this one

let imageSrc = ['c1.img', 'c2.jpg', 'c3.jpg'];
let imgIndex;
setInterval(()=>{
    if(imgIndex == undefined) {
        imgIndex = 0;
    } else {
        if(imgIndex >= imageSrc.length - 1) {
            imgIndex = 0;
        } else {
            imgIndex++;
        }
    }
    document.getElementById("carimg").src = imageSrc[imgIndex];
}, 2000);

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