0

I don't understand why beneath code is not working.

function doSome(){
    console.log("Hi");
}

setInterval(doSome(), '1000');

what I expected :

// every second
Hi
Hi
Hi
...

but result

TypeError: Cannot read property 'call' of undefined
    at wrapper [as _onTimeout] (timers.js:275:18)
    at Timer.listOnTimeout (timers.js:92:15)

Okay, If I change setInterval(doSome(), '1000'); to setInterval(function(){doSome()}, '1000'); The code works finely. But I don't know what is different, and why I have to wrap the function like function(){...} Can you tell me some hints, Thanks...

2
  • 5
    setInterval(doSome(), '1000'); ==> setInterval(doSome, 1000); when passing function as reference, use only function name. Remove () of doSome, time should not be string Commented Dec 29, 2015 at 3:44
  • 1
    Remove the parenthesis ().. you are invoking the function. You need to pass a reference, therefore it should be setInterval(doSome, 1000); Commented Dec 29, 2015 at 3:44

3 Answers 3

2

The problem with your code is setInteval expects the first argument to be a reference to a function, while doSome() will evaluate to some value, in this case null.

What you want is the following:

function doSome(){
  console.log("hi");
}
setInterval(doSome, 1000);

As you noted, you could also use an anonymous function (which returns a reference to that function), that calls the function you really want to execute. This is useful for calling a function that takes parameters.

function doMore(x, y){
  if (x < y)
    console.log("Hi");
  else
    console.log("Bye");
}
setInterval(function(){ doMore(0,1);}, 1000);

The second example is trivial but shows how you can call functions that require parameters using setInterval.

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

Comments

1

When you don't use anonymous function ie. named function then you're calling it using the parentheses so remove it and will work fine:

setInterval(doSome, 1000);//You still don't need to wrap interval time within string

Comments

1

The problem is that setInterval requires a function as it's first argument.
The beauty of JavaScript is that you could even return a function from doSome:

function doSome(param){
    return function() { console.log(param); }
}

setInterval(doSome("Hi"), 1000);

But of course the correct answer is:

function doSome(){
    return console.log("Hi");
}

setInterval(doSome, 1000);

Comments

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.