How to use settimeout function in the lightning component?
I am new to the lightning components and 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 in advance!
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); }
}
What are settimeout function?
Settimeout Function
The setTimeout function is a native JavaScript function. It sets a timer (a countdown set in milliseconds) for the execution of a callback function, calling the function upon completion of the timer.
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); });