setInterval for running a function with if statement not working

I need to use the setInterval function to run the function change() after every 3 seconds but what I have tried so far is not working:

    var image = document.getElementById("gif1");
    var image_tracker = '1gif' ; 
    function change() { 
     if(image_tracker =='1gif') { 
         image.src='2.gif' ; 
    	 image_tracker = '2gif' ; }
    else if (image_tracker ='2gif') { 
         image.src='3.gif' ; 
    	 image_tracker = '3gif' ; }
    else if (image_tracker = '3gif') {
         image.src='1gif' ; 
    	 image_tracker = '1gif' ; } }
    
    var timer = setInterval ('change () ; ' , 3000 ) ;
<img src="1.gif" id="gif1" alt="1.gif" style="width:400px;height:400px;border:1px solid black;">

Upvotes: 1

Views: 54

Answers (1)

AndrewL64
AndrewL64

Reputation: 16301

You have a bunch of syntax errors all over your code:

  1. Your elseif conditions are assignment operators = and should be replaced with a comparison operator such as the loose equality operator == or the strict equality operator === depending on your requirement [Check this article for an in-depth explanation of the differences between the two].

  2. You are assigning your setInterval() to a variable thus preventing it from running.

  3. You are referencing a string called change() inside your setInterval(). Remove the quotes since change is a function.


Check this jsFiddle or the Code Snippet below to see the gif change every 3 seconds:

var img = document.getElementById("gif1");

var image_tracker = '1gif';

function change() { 
 if(image_tracker == '1gif') { 
     img.src = '//media.giphy.com/media/13gvXfEVlxQjDO/giphy.gif'; 
     image_tracker = '2gif' ; }
	else if (image_tracker == '2gif') { 
     img.src= '//upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif'; 
     image_tracker = '3gif' ; }
	else if (image_tracker == '3gif') {
     img.src = '//colinbendell.cloudinary.com/image/upload/c_crop,f_auto,g_auto,h_350,w_400/v1512090971/Wizard-Clap-by-Markus-Magnusson.gif'; 
     image_tracker = '1gif' ;
	}
}

setInterval(change , 3000 ) ;
<img src="//colinbendell.cloudinary.com/image/upload/c_crop,f_auto,g_auto,h_350,w_400/v1512090971/Wizard-Clap-by-Markus-Magnusson.gif" id="gif1" alt="1.gif" style="width:400px;height:400px;border:1px solid black;" />

Upvotes: 3

Related Questions