2

I'm a bit new to lightning component and i'm trying to understand how can I use the settimeout function inside my component.

I'm trying to do this, but always getting errors and the component is crashing.

Thanks for the help !

My code:

({
init : function(component, event, helper) {
    helper.showSpinner(component);

    var isValid;
    var recordId = component.get("v.recordId"); 

    var action = component.get("c.functionFromClass");

    action.setParams({
        Id : recordId 
    });

    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS"){
            isValid = response.getReturnValue();
            alert(isValid);

            $A.get("e.force:closeQuickAction").fire();
            $A.get('e.force:refreshView').fire();
        }
        else{
            console.log("Unknown error");
            component.set("v.errorMessage", "Unknown error");
        }
        helper.hideSpinner(component);
    });
    $A.enqueueAction(action);
}

}

1
  • Can you show the error and where is the setTimeout code in the above snippet? Nov 7, 2020 at 10:27

1 Answer 1

3

As per doc, Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

An example of where you need to use $A.getCallback() is calling window.setTimeout() in an event handler to execute some logic after a time delay. This puts your code outside the framework's call stack.

This sample sets the visible attribute on a component to true after a five-second delay.

window.setTimeout(
    $A.getCallback(function() {
        cmp.set("v.visible", true);
    }), 5000
);

In your case, You can do like this:-

action.setCallback(this, function(response){
    var state = response.getState();
    if (state === "SUCCESS"){
        isValid = response.getReturnValue();
        window.setTimeout(
            $A.getCallback(function() {
                alert(isValid);
            }), 5000
        );
        $A.get("e.force:closeQuickAction").fire();
        $A.get('e.force:refreshView').fire();
    }
    else{
        console.log("Unknown error");
        component.set("v.errorMessage", "Unknown error");
    }
    helper.hideSpinner(component);
});
2
  • @Omnia Please check the update. Feb 12, 2020 at 8:49
  • Thanks for the help ! But is it possible to wrap all of the action.setCallback and not only the alert(isValid) part ? My purpose here is to limit the time of the callback
    – Omnia
    Feb 12, 2020 at 8:58

You must log in to answer this question.

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