setInterval函数返回undefined(setInterval function returning undefined)

编程入门 行业动态 更新时间:2024-10-24 15:25:26
setInterval函数返回undefined(setInterval function returning undefined)

我是第一次在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 。 有谁知道为什么会这样? 提前致谢!

I am learning setInterval in JavaScript for the first time, and am trying to show a value after 5 seconds. My code is given below:

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

I want 5 to be alerted, instead I am getting undefined. Does anyone know why this is happening? Thanks in advance!

最满意答案

您无法从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(); 
  
 

You can't return anything from the anonymous function within the setInterval call. You need to write to the console from within that function. Try this:

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(); 
  
 

更多推荐

本文发布于:2023-07-05 06:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034364.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   setInterval   undefined   returning   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!