Calling Apex method at regular interval from Lightning Component

Importance of $A.getCallback and Modifying Components Outside the Framework Lifecycle

Calling Apex method at regular interval in lightning component

Recently, I was in need of Lightning Component, which can poll Apex class at regular interval and display status of some process running in background. Initially, I thought its very easy and straight forward. Just like we do in Visualforce, use window.setInterval method of Javascript and I came up with below code.


 * @Author		:		Jitendra Zaa
 * @Date		:		Nov-09-2016
 * @Desc		:		This class is used by LEX component - PollApexClass
 * 			:		It returns total number of contacts in system
 * */

public class RefreshContactCounter {
    public static Integer getContactCount(){
         AggregateResult[] groupedResults = [SELECT count(Id) totalCount FROM Contact];
		Object totalCount = groupedResults[0].get('totalCount');
        return (Integer) totalCount ;



 <aura:component controller="RefreshContactCounter">    
    <aura:attribute type="Decimal" name="contactCount" />
     <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
<div class="slds"> 
<article class="slds-card slds-card--narrow">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media--center slds-has-flexi-truncate">
<div class="slds-media__figure">
                        <c:svg xlinkHref="/resource/SLDS_2_0_3/assets/icons/standard-sprite/svg/symbols.svg#contact" class="slds-icon slds-icon-standard-contact slds-icon--small" /> 
<div class="slds-media__body slds-truncate">

                            <span class="slds-text-heading--small"> Total Contacts in system</span>
<div class="slds-card__body slds-align--absolute-center slds-text-heading--large"> {!v.contactCount }</div>
<div class="slds-card__footer"> Refresh rate - every 5 seconds </div>


	doInit : function(component, event, helper) {
		helper.pollApex(component, event, helper);


    pollApex : function(component, event, helper) { 
        //execute callApexMethod() again after 5 sec each
    handleResponse : function (response, component){
        var retVal = response.getReturnValue() ;
    callApexMethod : function (component,helper){    
        var action = component.get("c.getContactCount");        
        action.setCallback(this, function(response) {
            this.handleResponse(response, component);

In above helper javascript file, we are using window.setInterval() method of Javascript, to call Apex class at interval of 5sec.

<aura:application >
    <ltng:require styles="/resource/SLDS_2_0_3/assets/styles/salesforce-lightning-design-system.css" />
 	<c:PollApexClass /> 

If we try to run above application, it doesn’t work as expected and returns below error

Windows setInterval error in Lightning Component
Windows.setInterval() error in Lightning Component

After going through documentation, I came across this page, which hints how we can modify Lightning component’s content outside its lifecycle.

In PollApexClassHelper.js file, we just need to change method pollApex by below code :

pollApex : function(component, event, helper) { 
        //execute callApexMethod() again after 5 sec each
            $A.getCallback(function() { 
            }), 5000

Demo :

poll apex class in lex compressor

Related posts

13 thoughts on “Calling Apex method at regular interval from Lightning Component”

  1. Superb finding! One of my Appexchange component uses similar real-time update approach. Will this approach show updated data without tap or click on component/window? Thanks for the share!

  2. Hi , Thanks for sharing this.Was very helpful.
    Also, I need to make a small change in this.
    Let say it the count record value = 40 , then this should stop calling or it should stop. I tried with :
    if(record count != 40)
    //run the code window.setInterval(
    else if(record count == 40)
    // do something else

    when I debug this , when the record count comes to 40 , still this is calling the apex action at 5 sec of interval.

    Can you please suggest some method to stop this time interval calling at some condtion.

    Thanks and regards
    Apoorv Jain

    1. Hi Apoorva,

      Yes we can kill polling by using such condition. I tried below logic and it works well.

      pollApex : function(component, event, helper) {

      //execute after 5 sec each till next case is not assigned
      var pollId = window.setInterval(
      $A.getCallback(function() {
      helper.callApexMethod(component, helper, pollId);
      }), 5000


      callApexMethod : function (component,helper,pollId){
      var action = component.get(“c.getContactCount”);
      action.setCallback(this, function(response) {
      this.handleResponse(response, component, pollId);

      handleResponse : function (response, component, pollId){
      var retVal = response.getReturnValue() ;
      //logic to kill polling
      if(retVal > 40){
      //This will kill your batch job

      Please let me know if it solves your purpose. Cheers.

  3. Hi @Rohit Pund
    I tried implementing the code that you have mentioned but I am getting error at calling helper.callApexMethod(component, helper, pollId); For me its showing error “Cannot read property ‘callApexMethod’ of undefined”. I tried it changing to this.callApexMethod(component, helper, pollId); and then it says “helper.callApexMethod(component, helper, pollId);” is not a function.

  4. Some issue in the code here.

    i have implemented the same logic for one of the component which is there on contact layout

    Step 1: user open a contact and did some actions and polling called
    Step 2: user went to account on the same browser tab
    Step 3: very immediately user come back to same contact where he did some actions last time

    in this case the polling method still calling and getting setcallback issue. if the time interval is more between contact to account to contact no issue is coming.

    I tried to find the polling apex id to kill the recursing job but it is null.

    Can you help to fix this

    1. I understand that polling method is keep on calling even we move to other tabs in the browser. The above code practically will not work. Is there any way we can do polling

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.