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();
更多推荐
发布评论