Haravi Haravi - 5 months ago 8
jQuery Question

Restarting Interval not working after clearing

I am getting num1 and num2 value from service call. I am trying reset interval after clearing it but it does not work this way. I have also tried other ways mentioned in stackoverflow. Nothing works.

d3.json('/service/dates', function(error,dates) {
var dran = dates;
if(dates != null){
sDt = new Date(dates.st);
eDt = new Date(dates.et);
var i = 0;
var start = function(){
if (sDt > eDt) {
clearInterval(interval);
flag = true;
console.log(fromDt);
console.log(toDt);
interval = setTimeout(start,200);
$('.wrapper').trigger('newPoint');
return;

}
var sDate = sDt.toISOString();
var eDate = new Date(sDt.setMinutes(sDt.getMinutes() + 30)).toISOString();

//Calling the api for graph values
d3.json("/service/dat?s=" +sDate+ "&e=" +eDate, function(error,results) {
if(results != null){

numbers = numbers.concat(results.numbers);
values[values.length] = results.values;
}
});
i++;
}
var interval = setInterval(start,10);
}
});
$('.wrapper').on('newPoint', function(){
if(flag){
if(count!=values.length){
tick(values[count]);
count++;
}
}
});

Answer

Put the entire API call inside a named function. Then call that from the start() function to restart everything.

function doAPILoop() {
  d3.json('/service/dates', function(error, dates) {
    var dran = dates;
    if (dates != null) {
      sDt = new Date(dates.st);
      eDt = new Date(dates.et);
      var i = 0;
      var start = function() {
        if (sDt > eDt) {
          clearInterval(interval);
          $('.wrapper').trigger('newPoint');
          doAPILoop();
          return;
        }
        var sDate = sDt.toISOString();
        var eDate = new Date(sDt.setMinutes(sDt.getMinutes() + 30)).toISOString();

        //Calling the api for graph values
        d3.json("/service/dat?s=" + sDate + "&e=" + eDate, function(error, results) {
          if (results != null) {

            numbers = numbers.concat(results.numbers);
            values[values.length] = results.values;
          }
        });
        i++;
      }
      var interval = setInterval(start, 10);
    }
  });
}

doAPILoop();
Comments