1

I stated to work with vue.js recently and I don't understand why this behavior happens, using the setTimeout(). With the following code, the function defined in setInterval(function(), time) is launched immediately no matter the value of 'time':

timerOn(){

  ...

  this.avatar.timer.data = setTimeout( this.timerFunction(), 10000);
},
timerFunction(){
  ...

  console.log('Hello!!');
  clearTimeout(this.avatar.timer.data);
  this.timerOn();
},

But if I use the following code all works fine and the function inside setInterval occurs after the 'time' defined:

timerOn(){

  ...

  var This = this;
  this.avatar.timer.data = setTimeout(function() { This.timerFunction()}, 10000);
},
timerFunction(){
  ...

  console.log('Hello!!');
  clearTimeout(this.avatar.timer.data);
  this.timerOn();
},

Someone can guide me and say why the first method fails?

Thank you.

1
  • 2
    In the first did you mean to say, this.timerFunction instead of this.timerFunction()? Commented Mar 21, 2017 at 15:42

1 Answer 1

5

This executes timerFunction immediately and passes the result as the callback to setTimeout.

setTimeout( this.timerFunction(), 10000)

But, you want to pass a callback to setTimeout and timerFunction does not return a function. I expect what you wanted was

setTimeout( this.timerFunction, 10000)

This passes a reference to the function, timerFunction to setTimeout. The first example, passes the result of timerFunction() to setTimeout.

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

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.