[英]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: 我需要使用
setInterval
函数在每3秒后运行一次函数change()
,但到目前为止我尝试过的函数不起作用:
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;">
You have a bunch of syntax errors all over your code: 您的代码中存在大量语法错误:
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]. 你的
elseif
条件是赋值运算符 =
并且应该用比较运算符替换,例如松散等式运算符 ==
或严格相等运算符 ===
具体取决于您的要求[检查本文以深入解释之间的差异二]。
You are assigning your setInterval()
to a variable thus preventing it from running. 您将
setInterval()
分配给变量,从而阻止它运行。
You are referencing a string called change()
inside your setInterval()
. 您正在
setInterval()
中引用一个名为change()
的字符串。 Remove the quotes since change is a function. 删除引号,因为更改是一个功能。
Check this jsFiddle or the Code Snippet below to see the gif change every 3 seconds: 检查下面的jsFiddle或代码片段 ,每3秒看一次gif更改:
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;" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.