[英]How do I break out of a function in javascript
If I have something like this:如果我有这样的事情:
var x = 1;
setInterval(function(){
if (x == "1") {x = "2"};
if (x == "2") {x = "3"};
if (x == "3") {x = "1"};
}, 250);
At the moment, the function runs the first if
since it is inherintly true, then since the first if
alters x
to meet the conditions of the second if
, it runs that as well, then does the same with the third and sets x
all the way back to 1
How do I get each of the if
functions to break out of the setInterval
funtion so that after it has ran, the other if
s will not run?目前,该函数运行第一个if
因为它固有地为真,然后由于第一个if
改变x
以满足第二个if
的条件,它也运行那个,然后对第三个执行相同的操作并设置x
所有回到1
如何让每个if
函数脱离setInterval
函数,以便在它运行后,另一个if
不会运行?
I've found how to do this with loops but not for functions.我已经找到了如何用循环而不是函数来做到这一点。 I understand that the above function would probably be better suited in a loop, but it's only an example for the sake of keeping the question short.我知道上面的函数可能更适合循环,但这只是为了保持问题简短的一个例子。
Use a ternary expression for this simple case:对于这个简单的情况,使用三元表达式:
var x = 1; var interval = setInterval(function() { x < 3 ? x++ : x=1 console.log(x) }, 250); // clears the interval after 5000 ms setTimeout(function() { clearInterval(interval) }, 5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.