html直到ajax函数结束才更新

时间:2017-04-15 19:16:25

标签: javascript jquery json ajax

我正在尝试在JavaScript中编写3秒倒计时功能。倒计时的开始是由服务器设置的,所以我有setInterval函数调用ajax函数,该函数在服务器上运行脚本以查看它是否准备好开始倒计时。如果设置了倒计时,则返回的数据是倒计时已准备好并将以指定的毫秒数开始。

我有以下功能,如果我单步执行,我可以逐步看到屏幕更新。但是,当我只是运行脚本时,它会批量更新所有内容。我不明白为什么?

        $.ajax({
            url : "/check_countdown/", // the endpoint
            type : "GET", // http method
            data : { info : info }, // data sent with the post request
            // handle a successful response
            success : function(json) {
                console.log(json);
                if (json.ready == 'True') {
                    // if we have a start_time then we get ready for the count down
                    console.log("Countdown ready to start!"); // sanity check
                    // stop pinging the server
                    clearInterval(countdownInterval);
                    // clear screen
                    $('#holdingImage').hide();
                    // show countdown block
                    $('#countdownText').show();
                    startTime = new Date().getTime() + json.milliseconds;
                    nowTime = new Date().getTime();
                    console.log("Every ", nowTime, startTime);
                    while (nowTime < startTime) {
                        nowTime = new Date().getTime();
                        }
                    $('#countdownText').html("<h1>Three</h1>");
                    startTime = startTime + 1000;
                    console.log("Second ", nowTime, startTime);
                    while (nowTime < startTime) {
                        nowTime = new Date().getTime();
                        }
                    $('#countdownText').html("<h1>Two</h1>");
                    startTime = startTime + 1000;
                    console.log("Counts ", nowTime, startTime);
                    while (nowTime < startTime) {
                        nowTime = new Date().getTime();
                        }
                    $('#countdownText').html("<h1>One</h1>");
                    } else {
                        console.log("Countdown NOT ready to start!"); // another sanity check
                        }
            },
            // handle a non-successful response
            error : function(xhr,errmsg,err) {
                $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                    " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
                console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
            }
        });

我认为更新之间的第二个(1000毫秒)应该足够了吗?

2 个答案:

答案 0 :(得分:0)

    $.ajax({
        url : "/check_countdown/", // the endpoint
        type : "GET", // http method
        data : { info : info }, // data sent with the post request
        async: false, //<---- Add this
        ....

仅添加(async:false)

答案 1 :(得分:0)

这是我提出的解决方案。我不相信它的功效,但是......

我将成功功能更改为:

            success : function(json) {
                console.log(json);
                if (json.ready == 'True') {
                    // if we have a start_time then we get ready for the count down
                    console.log("Countdown ready to start!"); // sanity check
                    console.log(json);
                    // stop pinging the server
                    clearInterval(countdownInterval);
                    // clear screen
                    $('#holdingImage').hide();
                    // show countdown block
                    $('#countdownText').show();
                    startTime = new Date().getTime() + json.milliseconds;
                    nowTime = new Date().getTime();

                    while (nowTime < startTime) {
                        nowTime = new Date().getTime();
                        }
                    startCountdown();
                    }

我添加了一个名为startCountdown()的新函数,它是:

    function startCountdown () {
        var display1 = document.querySelector('#countdownText'),
            startTime = 5,
            remainingTime = startTime,
            timer = new CountDownTimer(startTime);

        timer.onTick(format1).start();

        function format1(minutes, seconds) {
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display1.textContent = seconds;

            remainingTime = parseInt(minutes) * 60 + parseInt(seconds);

            if ((minutes=="00") && (seconds=="00")){
                console.log("time expired!");  // sanity check
            }

        }
    }

然后我使用了这个来自其他地方的timer.js脚本(我不知道我从哪里得到它所以不能归功于作者 - 抱歉)

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

CountDownTimer.prototype.stop = function() {
  this.running = false;
};

全押,它给了我想要的结果