1

I have this code in my lightning component helper where I want to call another method form the same helper.

window.setTimeout(
  $A.getCallback(function() {
    for(var key in someFieldsets){ 
      if(someFieldsets[key].fieldAPIName == 'sampleField__c' && !$A.util.isEmpty(someFieldsets[key].fieldValue)) {
        this.secondFunction(component);
      }
    }
  }), 2000
);

calling this.secondFunction(component); works when it is outside the setTimeout but when inside it, it doesn't perform the secondFunction anymore. what is the other option of calling a function within the helper? why does 'this' doesn't work this time?

4
  • May be your if condition is not making it happen. Comment if condition and try it. May 8, 2019 at 8:19
  • no, i tried to check through console.log inside the if statement. it returns a value.
    – Mae
    May 8, 2019 at 8:28
  • this context will not work in setTimeout. You need to pass that using bind. Check url stackoverflow.com/questions/2130241/… for complete understanding. May 8, 2019 at 8:48
  • i see... thanks
    – Mae
    May 8, 2019 at 9:09

2 Answers 2

2

this will not work in setTimeout. You need to pass that using bind. Check link for understanding.

0

In order to use asynchronous functions setInterval and setTimeout you need to bind the function passed to those methods to the current context (that is: your component itself).

Your component might be referenced all the time in your code using this, especially when accessing and changing its own attributes.

To bind the function to your current context, use .bind(this) on the function object. Remember: functions are first-class objects, which means that when you call a function the interpreter will return you a representation of it (an object). And that way you can call the .bind method.

So if your function is called doSomethingInOneSecond, for example, and you are calling it from a method in your component, you'll use it like this:

method() {
    setTimeout(function() {
        console.log('Hello one second after!')
    }.bind(this), 1000)
}

Note: the new(ish) JS syntax of using arrows => requires you to wrap your function with parenthesis:

setTimeout((() => {
    console.log('Hello one second after!')
}).bind(this), 1000)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .