如果有人帮助我,我将非常感激。我是JS的新手。我试图像我的全局变量一样多次调用函数。我的问题是函数同时执行。如何让它交替执行?这是我的代码:
#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;
}
答案 0 :(得分:1)
你需要一个间隔:
var interval;
var limit = 1;
var count = 0;
替换startGame:
function startGame()
{
interval = setInterval(browserturn, 1000);
limit++;
}
间隔以1000毫秒的间隔调用您的函数,并将控件释放到渲染器,因此您将看到更改
在browserturn中你可以递增计数器
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;
}
// --------------------------------------
}
如果计数是&gt;则清除间隔;限制
答案 1 :(得分:0)
您应该使用setTimeout
来延迟recursive
函数调用。我在下面写了一个基本的递归函数:
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);
&#13;
<div id="myDiv">
</div>
&#13;