[英]Run functions in a loop JavaScript/JQuery
我有一堆調用另一個函數的函數。 我想在一個無限循環中運行這些功能,而不能真正提出一個邏輯。
我的代碼如下所示:
<script>
function runAnim(x,y) {
//animation code
}
runAnim(a,2);
setTimeout(function() {
$('#a').fadeOut('fast');
}, 3000);
runAnim(b,4);
setTimeout(function() {
$('#b').fadeOut('fast');
}, 3000);
</script>
所以我想在無限循環中運行這兩個'runAnim'函數。 我試過了
while(1) {}
但這掛斷了我的瀏覽器。 我嘗試實現setInterval方法,但不知道該怎么做。 如果您願意,我可以發布runAnim(x,y)函數以獲得更多的清晰度。
更改runAnim
方法以通過setTimeout
包含對runAnim
的調用,以便您可以進行無限循環,同時確保不超過最大堆棧數 。
function runAnim(x,y) {
//animation code
if ( y == 2 )
{
setTimeout( () => {
runAnim(x,4);
$('#a').fadeOut('fast'); //call the fadeout here itself
}, 3000 );
}
else
{
setTimeout( () => {
runAnim(x,2);
$('#a').fadeOut('fast');
}, 3000 );
}
}
您不需要顯式的無限循環,只需讓這些函數一遍又一遍地調用另一個函數即可
這是鏈接的示例:
function fadeOutA() { $('#b').fadeIn('fast'); $('#a').fadeOut('fast', fadeOutB); } function fadeOutB() { $('#a').fadeIn('fast'); $('#b').fadeOut('fast', fadeOutA); } function stop() { $('#a, #b').stop(); } $('#start').click(fadeOutA); $('#stop').click(stop);
div { width: 50px; height: 50px; float: left; margin: 10px; } #a { background-color: green; } #b { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="a"></div> <div id="b"></div> <button id='start'>START</button> <button id='stop'>STOP</button>
我建議不要編寫任何運行無限循環的邏輯,因為這會給您的瀏覽器造成問題。 但是,如果您希望完成此操作,請執行以下操作
for(var i=0;;i++){}
創建for循環,然后將函數放入此循環中,該循環將無限執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.