$A.getCallback() usage for polling in Lightning Component

$A.getCallback() usage for polling in Lightning Component

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.

Sample Code:


Component:


<aura:component implements=”force:appHostable”>
    
    <aura:attribute type=”Integer” name=”count” default=”1″/>
    
    <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>
    <div class=”slds-box slds-theme_default”>
        {!v.count}
    </div>
        

</aura:component>


Controller:


({
    doInit : function(component, event, helper) {
        //execute again after 5 sec each
        window.setInterval(
            $A.getCallback(function() { 
                helper.increment(component,helper);
            }), 5000
        ); 
    }

})


Helper:


({
increment : function(component, event) {
var i = component.get(“v.count”);
        component.set(“v.count”, i+1);
}

})


Output:

Leave a Reply