如何在我的函数中嵌套setInterval和setTimeout?

问题描述 投票:0回答:1

早上好,

我有一个javascript函数,该函数依次调用了几个函数。我想在调用javascript函数后半秒触发该函数(在下面的示例中为check1),然后每10秒(10000毫秒)调用一次相同的函数check1。做完一些研究后,我发现-虽然可能是错的-setInterval和setTimeout的组合可以达成协议。

不幸的是,结果与预期不符。

[之后,我使用clearInterval()进行了第二次尝试,但是我不确定如何嵌套这些各种功能。

是否有一种优雅而聪明的方法来实现这一目标?预先非常感谢您的帮助

以下是我的JavaScript代码:

// Global variables
var AutoScript = false;
var IntervalRefresh1 = 500;
var newIntervalDefined1 = false;

// calls the startUp method
startUp();


function startUp()
{
  console.log("I'm the startup2");
  setInterval(check1, IntervalRefresh1);
}


function check1()
{
  $.ajax({
  type: 'POST',
  url: 'php/checker1.php',
  dataType: 'json',
  data: {
  counter:$('#message-list').data('counter')
  }
  }).done(function( response ) {
  /* check if with response we got a new update */
  if(response.update==true)
  {
    var j = response.news;      
    $('#message-list').html(response.news);
    AutoScript = true;
    // here I call a specific method named after getDataFromDatabase(j);
    AutoScript = false;        
    if (newIntervalDefined1 == false)
    {
      setTimeout(check1, 10000);
      newIntervalDefined1 == true;
    }
  }
  });
}
javascript settimeout setinterval
1个回答
0
投票

请勿将setInterval与异步/ ajax一起使用

只需使用setTimeout

// Global variables
var AutoScript = false;
var IntervalRefresh1 = 500;

function check1() {
  $.ajax({
    type: 'POST',
    url: 'php/checker1.php',
    dataType: 'json',
    data: {
      counter: $('#message-list').data('counter')
    }
  }).done(function(response) {
    /* check if with response we got a new update */
    if (response.update == true) {
      var j = response.news;
      $('#message-list').html(response.news);
      AutoScript = true;
      // here I call a specific method named after getDataFromDatabase(j);
      AutoScript = false;
      setTimeout(check1, 10000);
    }
  });
}
$(function() {
  check1()
})
© www.soinside.com 2019 - 2024. All rights reserved.