Reputation: 107
I have written some code in Javascript that draws a star pattern upon a button press. When the button is pressed, 4 different segments of the pattern are appended to 4 different divs. They all fall under the same function code:
function myFunction() {
$('#Asterisk').empty();
$('#Getafix').empty();
$('#upsidedown').empty();
$('#downsideup').empty();
for (var i = 0; i < 7; i++) {
for (var a = i; a < 7; a++) {
$('#Asterisk').append("*");
}
$('#Asterisk').append("<br>");
for (var a = i; a > -1; a--) {
$('#Getafix').append("*");
}
$('#Getafix').append("<br>");
for (var a = i; a > -1; a--) {
$('#upsidedown').append("*");
}
$('#upsidedown').append("<br>");
for (var a = i; a < 7; a++) {
$('#downsideup').append("*");
}
$('#downsideup').append("<br>");
}
}
myFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Asterisk"></div>
<div id="Getafix"></div>
<div id="upsidedown"></div>
<div id="downsideup"></div>
Now I need to be able to make all of the individual stars in those separate segments appear at a certain timing. i.e, the first star in the pattern appended to the 'Asterisk' div, appears 2 seconds after the button press, and then the second star appears after another 2 seconds, so on and so forth. I know that I can use the Timeout function in Javascript to achieve this, but I'm not sure how to make it work for different BLOCKS of code as opposed to making it work for different functions. I don't necessarily want answers that give me the code straight away, I just want an idea as to how I can achieve this so that I can write the code myself. Any coherent explanation would do. A friend of mine suggested using IF conditions to make a star with an odd index to appear for 2 seconds, and one with an even index to appear again with the same timing (Or a different timing, if I please). but am still not sure how to implement the Timeout function for individual blocks of code, and how it would work in this situation.
Upvotes: 0
Views: 107
Reputation: 1579
for a start you need to put the timeout function inside each loop if you want to put an interval for each * to show
ie
for(var a=i;a<7;a++) {
setTimeout(function(){ $('#Asterisk').append("*");
},Your_time_in_milliseconds)
}
like this you neeed to go if yo put the for loop inside the timeout function it wont work as desired now try to change the code accordingly keeping this in mind
Upvotes: 2