user3033194 user3033194 - 3 months ago 25
jQuery Question

setInterval function returning 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!

Answer

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