Illusion
Illusion

Reputation: 1

how to stop to call the same function again and again in JavaScript?

here is the HTML code, while clicking on clearfix class function called will happen and it will run the same function 4 times .

<div class="clearfix">
    <ul id="dashboard-tab" class="nav nav-tabs pull-left">
        <li class="active" isdashboardloaded="true">
            <a data-toggle="tab" href="#dashboard_5" aria-expanded="true">DashLoadingLineChart</a>
        </li>
        <li class="" isdashboardloaded="true">
            <a data-toggle="tab" href="#dashboard_6" aria-expanded="false">Zoom</a>
        </li>
    </ul>
</div>

JS function

$(document).on('click','.clearfix',function(){
    var dashId=$('.dashboardTabContent.active').attr('id');
    var dash_ids = bu.angular.pageScope.dashboardCollection.collection;
    var dashBoardUrl=event.target.href;
    $.each(dashObj.widgetObj,function(widgetId,widgetObj){
        clearWidget(widgetId,widgetObj.mode);
        var widget_refresh_interval = widgetObj.refresh_interval;
        //widgetInterval[widgetId] = 0;
        clearInterval(widgetInterval[widgetId]);
        bu.angular.pageScope.$digest();
        widgetWiseReload(widgetId,dashId)
        getWidgetData(widgetId,dashId,widgetObj,data_sources);
    });
});

i need to run this function only one time, but it is running more than 2 times .

Upvotes: 0

Views: 750

Answers (2)

may
may

Reputation: 33

// define a function of runOce
function runOnce(fn) {
  var isDone = false;
  return function(){
    if(isDone){
      return;
    }
    isDone = true;
    fn();
  };
}

// demo
function youWantRunFn(){
  alert(0);
}
var changeYourFn = runOnce(youWantRunFn);
// now,changeYourFn only can run once
changeYourFn(); // alert 0
changeYourFn(); // nothing

Upvotes: 0

Maybe you are attaching the function more than one time. Try this:

$(document).off("click", ".clearfix").on('click','.clearfix',function() {
    $.each(dashObj.widgetObj,function(widgetId,widgetObj){
        clearWidget(widgetId,widgetObj.mode);
        var widget_refresh_interval = widgetObj.refresh_interval;
        //widgetInterval[widgetId] = 0;
        clearInterval(widgetInterval[widgetId]);
        bu.angular.pageScope.$digest();
        widgetWiseReload(widgetId,dashId)
        getWidgetData(widgetId,dashId,widgetObj,data_sources);
    });
});

This will detach the event before attaching it again, so if is called more than one time, it will be attached one time, actually.

Protip: Keep your indentation clean.

Protip 2: If this was the problem, then you should look why this code is called more than one time instead of using this hack.

Upvotes: 1

Related Questions