javascript - setInterval 函数返回未定义

标签 javascript jquery

我是第一次学习 JavaScript 中的 setInterval,并试图在 5 秒后显示一个值。我的代码如下:

<button onclick="myTest()">Try it</button>

<script>
function myTest() {
    const ret = myFunction();
    alert(ret);
}

function myFunction() {
    let i = 0;
    const interval = setInterval(function(){ 
        i += 1;
        if (i === 5) {
            clearInterval(interval);
            return i;
        }
    }, 1000);
}
</script>

我想提醒 5,但我得到的是 undefined。有谁知道为什么会这样?提前致谢!

最佳答案

您不能从 setInterval 调用中的匿名函数返回任何内容。您需要从该函数中写入 console。试试这个:

function myTest() {
  // this function is now redundant - you could call myFunction() directly
  myFunction();
}

function myFunction() {
  let i = 0;
  const interval = setInterval(function() {
    i += 1;
    if (i === 5) {
      clearInterval(interval);
      console.log(i); // this will appear after 5 seconds...
    }
  }, 1000);
}

myTest();

关于javascript - setInterval 函数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223622/

相关文章:

javascript - 无法从具有隔离范围的指令内访问 Controller 中定义的对象

javascript - 如何将外部 javascript 文件添加到目录中的所有 html 文件中?

javascript - 发送 xhrPost 请求时 DOJO 'TypeError:Cannot read property ' style of null 错误响应

jquery - 如何使用 jQuery 和 ASP.NET MVC 从 AJAX 调用返回错误消息?

javascript - 悬停按钮下拉菜单上的 Bootstrap

javascript - 禁用复选框的其他方法?

javascript - 查找数组中每个数组的平均值

javascript - 带有输出百分比的jquery自定义字符串比较函数

jquery - 我如何使用 jquery 获取除按钮和隐藏字段之外的所有输入?

php - 根据宽度计算横幅的高度