如何在 JS 中调用 2 次或更多次时延迟函数执行

How to delay function execution when it calls 2 and more times in JS?

本文关键字:时延 延迟 执行 函数 JS 调用      更新时间:2023-09-26

下面是我的代码的链接。请点击按钮几次,以了解我的意思。我正在尝试多次调用同一个函数,并在函数调用之间间隔。请帮助我。 http://codepen.io/arminemash/pen/KzBBjN

.HTML

<div id='generalwrapper'> 
    <div id='general'>                  
        <div  id='1' class='cell' onclick='simon(this.id)'></div>
        <div  id='2' class='cell' onclick='simon(this.id)'></div>           
        <div  id='3' class='cell'  onclick='simon(this.id)'></div>
        <div   id='4' class='cell'   onclick='simon(this.id)'></div>
     </div> 
    <div id='buttondiv'>
        <button onclick='startGame()'>On</button>
    </div>
</div>

JavaScript

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;
}

这将保证所有游戏之间有100毫秒的间隔

var tasks = []
var createTask = function(task) {
  tasks.push(function() {
      task(function() {
        tasks.shift()
        var next = tasks[0]
        next()
    })
  })
  if (tasks.length === 1) {
     tasks[0]()
  }
}
var startGame = function() {
  createTask(function(next) {
    ... // whatever happens
    // if ready call next
    setTimeout(next, 1000)
  })
}

http://codepen.io/lipp/pen/eZjopG

相关文章: