0

I have a question about setTimeout, my code follows:

<script type="text/javascript">
    var s =-1;
    setImage();
    function setImage(){
        var img=new Array();
        var url=new Array();
        img[0]="images/oak.gif";url[0]="http://oakland.athletics.mlb.com/";
        img[1]="images/was.gif";url[1]="http://washington.nationals.mlb.com/";
        img[2]="images/chc.gif";url[2]="http://chicago.cubs.mlb.com/";
        img[3]="images/sd.gif";url[3]="http://sandiego.padres.mlb.com/";
        s+=1;
        if(s>=img.length){
            s==0;
        };
        document.getElementById("imgsrc").src=img[s];
        document.getElementById("imghref").href=url[s];
        setTimeout(setImage,1000);
    };
</script>

And I'm confused as to why I can't change var s=-1 in the function setImage(), like:

        **var s=-1**
        s+=1;
        if(s>=img.length){
            s==0;
        };

The function doesn't work. I thought the problem is about global and local variable, but I don't have a clear view.

the code result will be

		var s =-1;
		setImage();
		function setImage(){
			var img=new Array();
			var url=new Array();
			img[0]="https://imgur.com/sfAyT6s.gif";url[0]="http://oakland.athletics.mlb.com/";
			img[1]="https://imgur.com/av5hb4a.gif";url[1]="http://washington.nationals.mlb.com/";
			img[2]="https://i.imgur.com/zGKLMPh.gif";url[2]="http://chicago.cubs.mlb.com/";
			img[3]="https://i.imgur.com/ZBXTL5s.gif";url[3]="http://sandiego.padres.mlb.com/";
			s+=1;
			if(s>=img.length){

				s=0;
			};
			document.getElementById("imgsrc").src=img[s];
			document.getElementById("imghref").href=url[s];
			setTimeout(setImage,1000);
		};
	...
	<div>	
		<a id="imghref" href="http://chicago.cubs.mlb.com/">
			<img id="imgsrc" src="images/chc.gif">
		</a>
	</div>
	...

3
  • For completeness, please add the result you're getting right now. You might also want to add console logging (at least for the values of s and img.length) and share the results of that. That will help you as well as the forum members to troubleshoot the code. Are any images displaying? Is the setTimeout called as expected? Commented Aug 26, 2018 at 3:48
  • typo in s==0? should be s=0 Commented Aug 26, 2018 at 3:50
  • I write wrong, the code should be s=0, thanks. Commented Aug 26, 2018 at 9:07

1 Answer 1

1

In your if statement, you wrote s==0. The == operator is a comparison operator. It's asking "is s equal to 0?" If your intention was to set s to zero, then write s=0 instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.