重新启动javascript setTimeout

时间:2017-07-03 02:50:00

标签: javascript jquery ajax

我有一个使用javascript setTimeout从数据库获取数据的脚本,但我需要知道如何重新启动此setTimeot以再次检查数据库如何在不使用setInterval的情况下执行此操作。

var update = 0;
var chatUpdate = setTimeout(function () {
  $.ajax({
      type: "GET",
      url: "get_chat.php",
      dataType: "html",
      success: function (response) {
          $(".msgView").html(response);
          if (response !== lastResponse) {
              var audio = new Audio('audio/solemn.mp3')
              audio.play()
          }
          lastResponse = response
      }
  });
}, 2000);

感谢。

2 个答案:

答案 0 :(得分:3)

您可以将函数设置为变量,然后再次调用setTimeout。

var update = 0;
var chatUpdate = function () {
    $.ajax({
        type: "GET",
        url: "get_chat.php",
        dataType: "html",
        success: function (response) {
            $(".msgView").html(response);
            if (response !== lastResponse) {
                var audio = new Audio('audio/solemn.mp3')
                audio.play()
            }
            lastResponse = response
            setTimeout(chatUpdate, 2000);
        }
    });
};
setTimeout(chatUpdate, 2000);

答案 1 :(得分:-1)

试试这个

var update = 0;
var chatUpdate = function () {
    $.ajax({
        type: "GET",
        url: "get_chat.php",
        dataType: "html",
        success: function (response) {
            $(".msgView").html(response);
            if (response !== lastResponse) {
                var audio = new Audio('audio/solemn.mp3');
                audio.play();
            }
            lastResponse = response;
        }
    });
};
setTimeout(chatUpdate, 2000);