首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何暂停间隔,等待函数响应,然后重新运行

如何暂停间隔,等待函数响应,然后重新运行
EN

Stack Overflow用户
提问于 2018-08-08 06:40:57
回答 1查看 62关注 0票数 0

正如你在这里看到的,我有一个小函数,它将强制玩家去特定的坐标。基本上作为一个函数参数,我设置了我想让玩家转到的坐标数组。正如你在下面的例子中看到的,当它命中其他位置时,这意味着玩家停留在特定的坐标上。它将+1加到index上,所以它将得到第二个坐标。我试图在"else“标签中运行一个函数,如果该函数返回true,我现在就想运行位于"else”标签上的代码。我怎样才能做到这一点呢?

代码语言:javascript
复制
var player = {
    x: 21,
    y: 24
}

function goCoords(data) {
    var index = 0;
    var i = setInterval(function() {
        if (index < data.length) {
            var coords = data[index];
            if (!(Math.abs(player.x - coords.x) <= 0 && Math.abs(player.y - coords.y) <= 0)) {
                //go(coords.x, coords.y); It will trying to go to these coords
            } else {
                //If on coords, run a function, and wait for return true
                //And run the code below again
                if (index < coords.length) {
                    index++;
                }
            }
        } else {
            clearInterval(i);
        }
    }, 150);
}

goCoords([{ x: 21, y: 24 }, { x: 21, y: 29 }]);

EN

回答 1

Stack Overflow用户

发布于 2018-08-08 07:59:23

ttl设置为您希望运行相同代码的数量。

代码语言:javascript
复制
async function goCoords(data) {
  // ...
  else {
    await recursiveFunction(...)
  }
}

async recursiveFunction(..., ttl = 2) {
  if (ttl < 1) {
    return
  }
  let result = await theFunctionThatMayReturnTrue()
  if (result) {
    // code to be executed n times (n = ttl)
    await recursiveFunction(..., --ttl)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51736385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档