如何在$ .when函数中具有SetInterval()

时间:2019-07-03 01:40:43

标签: javascript jquery setinterval getjson .when

这是对this question的后续行动。

我有一组功能,这些功能必须一个接一个地运行。当从外部链接解析2个JSON文件时,第一个函数($.when())开始。但是,我想每秒解析一次JSON文件。这就是我坚持的地方。 这是我的代码示例:

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>

我希望每秒调用_parseJSON()以获取最新数据。然后根据结果,_cacheOptions_render函数将得到更新。

我知道我应该为此设置间隔,但是我不知道如何实现。 如果有可能,我希望仅每秒更新一次上述功能,那么更新所有功能将太繁琐。

任何建议都会很棒。 预先感谢。

1 个答案:

答案 0 :(得分:0)

您可以简单地在setInterval块中编写相同的更新代码,并将其添加到您的代码中以下:

// 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)

稍后,您可以在需要时取消这些重复执行。

clearInterval(intervalId);

但是,在Internet环境中,每秒执行一次HTTP请求并不是一种适当的方式,因为它可能给客户端带来沉重的负担。 5或10秒根据您的需求将是理想的。希望对您有所帮助。干杯!