0

In javascript, why does this code work?

var myVar=setInterval(
   function(){
      myTimer()
   },1000
);

function myTimer()
{
   var d=new Date();
   var t=d.toLocaleTimeString();
   document.getElementById("demo").innerHTML=t; //displays time
   dpcument.getElementById("demo2").innerHTML = myVar; //displays 1
}

Why does myVar hold the value 1 even if I am not returning anything from the function?

3 Answers 3

5

setInterval returns a value, not your function. It returns an intervalID, so you can clear it with clearTimeout.

Sign up to request clarification or add additional context in comments.

Comments

2

myVar holds the return value of the call to setInterval irrespective of the fact that you have declared an anonymous function.

Comments

0

myVar will take the return value of the call to setInterval, not of the anonymous function you're passing, neither from myTimer.

Here is how it works:

  1. You call setInterval, which returns a timer id. You pass it a reference to an anonymous function.
  2. When the interval expires, the anonymous function is called (internally). It returns undefined (but it doesn't matter, since it's called internally, and that return value is never used).
  3. Every time the anonymous function is invoked, it calls myTimer, which also returns undefined. That is never used inside your anonymous function.

1 Comment

To whoever downvoted: I'd like to know what's wrong with my first sentence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.