简体   繁体   English

用更简单的循环替换递归函数

[英]Replacing recursive function with simpler loop

I'm new to the concept of recursion. 我是递归概念的新手。 I've been practicing JavaScript with some codes from javascript30.com. 我一直在用来自javascript30.com的一些代码练习JavaScript。 I've stumbled upon the below mention function: 我偶然发现了以下提到的功能:

function peep() {
    const time = randomTime(200, 1000); 
    const hole = randomHole(holes);
    hole.classList.add('up');
    setTimeout(() => {
      hole.classList.remove('up');
      if (!timeUp) peep();
    }, time);
  }

Link to full code: https://codepen.io/luckyseven444/pen/bXqXbP (code is running ok in my PC) 链接到完整代码: https : //codepen.io/luckyseven444/pen/bXqXbP (代码在我的PC上运行正常)

Is it possible to form a simple loop rather than the recursive function peep() mentioned above? 是否可以形成一个简单的循环而不是上面提到的递归函数peep()? I mean I want to replace the second peep() inside setTimeout function. 我的意思是我想替换setTimeout函数中的第二个peep()。

Thanks 谢谢

If you really insist, you can create an async function, wrap setTimeout with a Promise , await the Promise and add a loop: 如果您真的坚持,则可以创建一个async函数,用Promise包装setTimeout ,等待Promise并添加一个循环:

 async function test() { for (let i = 0; i < 10; i++) { console.log('before setTimeout', i); await new Promise(resolve => setTimeout(() => { console.log('timeout elapsed', i); resolve(); }, 1000)); } } test(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM