2017-05-20 2 views
-1

Ich habe einige JQuery, die divs zufällig auf einer Seite setzt. Derzeit macht es das jedoch unendlich.Ausführen einer Funktion eine bestimmte Anzahl von Malen in Jquery

Wie kann ich es für eine bestimmte Zeit laufen lassen und dann stoppen?

$(document).ready(function() { 
 
    makeDiv(); 
 

 
var count = 1; 
 
    function makeDiv() { 
 
    
 
    count ++; 
 
    while (count < 50){ 
 
     var numRand = Math.floor(Math.random() * 501); 
 
     var divsize = 100; 
 
     var posx = (Math.random() * ($('body').width() - divsize)).toFixed(); 
 
     var posy = (Math.random() * ($('body').height() - divsize)).toFixed(); 
 
     $newdiv = $("<div class='exploding'></div>").css({ 
 
     'left': posx + 'px', 
 
     'top': posy + 'px' 
 
     }); 
 
     $newdiv.appendTo('body').delay(2000).fadeIn(100, function() { 
 
     //$(this).remove(); 
 
     makeDiv(); 
 
     }); 
 
    } 
 
    } 
 
});
body, html { 
 
    width: 960; 
 
    height: 100%; 
 
} 
 
div.box { 
 
    position: relative; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
div.exploding { 
 
    position: absolute; 
 
    width: 10px; 
 
    height: 10px; 
 
    background-color: red; 
 
}

Antwort

0

Deklarieren der count mit im Inneren des makeDiv statt global .And hinzuzufügen count++ innerhalb des Endes der while-Schleife sein. nicht verwenden innerhalb des gleichen while.they makeDiv() while-Schleife Überlastung

$(document).ready(function() { 
 
    makeDiv(); 
 

 

 
    function makeDiv() { 
 
    var count = 1; 
 
    
 
    while (count < 50){ 
 
     var numRand = Math.floor(Math.random() * 501); 
 
     var divsize = 100; 
 
     var posx = (Math.random() * ($('body').width() - divsize)).toFixed(); 
 
     var posy = (Math.random() * ($('body').height() - divsize)).toFixed(); 
 
     $newdiv = $("<div class='exploding'></div>").css({ 
 
     'left': posx + 'px', 
 
     'top': posy + 'px' 
 
     }); 
 
     $newdiv.appendTo('body').delay(2000).fadeIn(100, function() { 
 
     $(this).remove(); 
 
     // makeDiv(); 
 
     }); 
 
     count ++; 
 
    } 
 
    } 
 
});
body, html { 
 
    width: 960; 
 
    height: 100%; 
 
} 
 
div.box { 
 
    position: relative; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
div.exploding { 
 
    position: absolute; 
 
    width: 10px; 
 
    height: 10px; 
 
    background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

count++; hat innerhalb der while-Schleife

Verwandte Themen