-3

I have a javascript function as shown below.

    function checkEven(number){
      return(number % 2 == 0 ? true : false)

      setTimeout(checkEven(number), 2000)
    }

I want to call checkEven function within every 2 seconds. but it is not working.

But then I tried the following code. It working fine and print method gets called in every 2 seconds.

    function print(){
      console.log(new Date());
      setTimeout(print, 2000)
    }

I want to understand why the first code didn't work. I need help with this.

Lanka
  • 29
  • 2
  • 11
  • In the first code you're not passing a function to `setTimeout`. You're passing the result of a function call. – jabaa May 13 '22 at 09:00
  • 1
    Does this answer your question? [In JavaScript, does it make a difference if I call a function with parentheses?](https://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses) – jabaa May 13 '22 at 09:01
  • Does this answer your question? [Javascript recursion settimeout](https://stackoverflow.com/questions/5559510/javascript-recursion-settimeout) – Dani3le_ May 13 '22 at 09:02
  • 1
    If you want to call checkEven every 2 seconds, you should use setInterval. – The KNVB May 13 '22 at 09:03
  • 1
    You are returning data and calling setTimeout only **after**. – Dani3le_ May 13 '22 at 09:03

1 Answers1

1

If you want to call the function every 2 seconds you should use setInterval():

const myLoop = setInterval(myFunc, 2000);

function myFunc() {
    console.log("Hello World");
}

clearInterval(myLoop); //If you want to stop the loop.

Also, in your code you are using setTimeout() only after the return. So, if it worked, the setTimeout(checkEven(number), 2000) would have a number as a parameter instead of a Func.

Dani3le_
  • 1,257
  • 1
  • 13
  • 22