I will be very grateful if somebody helps me.I am new in JS.I am trying to call a function as many times as my global variable is.My problem is the function executes simultaneously. How to make it execute alternately? Here is my code:
#general{width:400px;height:400px;margin:0 auto;}
.cell{width:50%;height:50%;color:black}
.cell:nth-of-type(1){float:left;background: #81E058}
.cell:nth-of-type(2){float:right;background: red}
.cell:nth-of-type(3){float:left;background: blue}
.cell:nth-of-type(4){float:right;background: yellow}
<div id='generalwrapper'>
<div id='general'>
<div class='cell' onclick='simon(this.id)'></div>
<div class='cell' onclick='simon(this.id)'></div>
<div class='cell' onclick='simon(this.id)'></div>
<div class='cell' onclick='simon(this.id)'></div>
</div>
<div id='buttondiv'>
<button onclick='startGame()'>On</button>
</div>
</div>
var browser=[];
var count=1;
function startGame(){
for(var i=0;i<count;i++){
browserturn();
}
count++;
}
function browserturn(){
var x=getNumber();
var element=x.toString();
browser.push(element);
var y=document.getElementById(element);
y.click();
$(y).delay(100).fadeOut().fadeIn('slow');
}
function getNumber(){
var randomNumber=Math.floor((Math.random() * 4)+1);
return randomNumber;
}
you need an interval:
var interval;
var limit = 1;
var count = 0;
replace startGame for this:
function startGame()
{
interval = setInterval(browserturn, 1000);
limit++;
}
The interval calls your function withi intervals of 1000 miliseconds, and releases the control to the renderer, so you will see the changes
in browserturn you can increment the counter
function browserturn(){
var x=getNumber();
var element=x.toString();
browser.push(element);
var y=document.getElementById(element);
y.click();
$(y).delay(100).fadeOut().fadeIn('slow');
// --------------------------------------
counter++;
if(counter < limit)
{
clearInterval(interval);
count = 0;
}
// --------------------------------------
}
and clear the interval if count is > to limit
You should use setTimeout
to delay a recursive
function call. I've written a basic recursive function below:
var myDiv = document.getElementById('myDiv'); var timesToRepeat = 4; function myRecursiveFunction(count) { myDiv.innerText += " ..." + count; count++; //increment count //this is our exit condition -- otherwise it recurs infinitely!! if (count <= timesToRepeat) { setTimeout(function() { //after 600ms, call our function again myRecursiveFunction(count); }, 600) } } //our initial call to the function myRecursiveFunction(1);
<div id="myDiv"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.