'javascript setTimeout()

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.



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dani3le_