0

This is a follow up to this question.

I have a set of funtions that has to run one after another. The first function ($.when())starts when 2 JSON files are parsed from external links. However, I would like the parse the JSON files once every second. This is where I stuck. Here is a sample of my code:

var myJSON;

function _parseJSON() {
  // return here, no need returning exactly what you would expect anyhow
  return $.getJSON(settings.json_src);
}

// because you returned, you can chain everything nicely together
$.when( _parseJSON() )
  // don't forget the argument here
  .then(function( data ) { myJSON = data; })
  // and these will only run after the myJSON got set
  .then( _cacheOptions )
  .then( _cacheDom )
  .then( _events )
  .then( _render );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I want _parseJSON() to be called every second to get the latest data. Then based on the result of that, _cacheOptions and _render functions will get updated.

I know I should use set intervals for this, but I dont know how to implement that. If it is possible I prefer only the mentioned functions get updated every second, It would be too heavy to update the all functions.

Any suggestions would be great. Thanks in advance.

Danny
  • 79
  • 3

1 Answers1

0

You can simply write the same update code inside a setInterval block and add it below to your code:

// because you returned, you can chain everything nicely together
$.when( _parseJSON() )
  // don't forget the argument here
  .then(function( data ) { myJSON = data; })
  // and these will only run after the myJSON got set
  .then( _cacheOptions )
  .then( _cacheDom )
  .then( _events )
  .then( _render );

var intervalId = setInterval(function(){

  // below will start after a second and hereafter execute every second!

  $.when( _parseJSON() )
    .then(function( data ) { myJSON = data; })
    .then( _cacheOptions )
    .then( _render );

}, 1000)

Later, you can cancel these repetitive executions when you need it.

clearInterval(intervalId);

However, executing an HTTP request on every second in an internet environment is not a proper way that can cause a heavy burden for clients as I think. 5 or 10 seconds according to your needs would be ideal. I hope it helps. Cheers!

Yavuz Tas
  • 344
  • 3
  • 16