Javascript开始倒计时,最后调用ajax

时间:2018-04-12 04:48:13

标签: javascript

我正在尝试使用以下Javascript代码启动Javascript倒计时。这是从 5 - 0 算起的。

现在我想要当它 0 然后我将调用Ajax请求(我知道如何做)。但是现在,我设置了会话结束的警告信息。

它不断向我显示警告信息但它应该一次!

这是JS代码:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;


        if(timer !== 0 ) {
            --timer;
        } else if( timer == 0 ) {
            alert('Your time has been completed.');
        }
    }, 1000);
}

window.onload = function () {
    var seconds = 5,
        display = document.querySelector('#time');
        startTimer(seconds, display);
};

3 个答案:

答案 0 :(得分:1)

您需要将间隔分配给变量,以便您可以在最终alert之后清除间隔,以便它不再运行:

&#13;
&#13;
function startTimer(duration, display) {
  let timer = duration;
  const interval = setInterval(function() {
    let minutes = parseInt(timer / 60, 10)
    let seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ":" + seconds;
    if (timer !== 0) {
      --timer;
    } else if (timer == 0) {
      alert('Your time has been completed.');
      clearInterval(interval);
    }
  }, 1000);
}

window.onload = function() {
  var seconds = 5,
    display = document.querySelector('#time');
  startTimer(seconds, display);
};
&#13;
<div id="time"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要使用clearInterval()方法,如下所示

var myVar = setInterval(function(){ myTimer() }, 1000);
myTimer() {
  if(conditionMet)
   clearInterval(myVar);
}

或仅供参考,您可以使用interval of react js

import { interval } from 'rxjs/observable/interval';

//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => {
 if(conditionmet)
   source.unsubscribe(); 
 console.log(val);
});

答案 2 :(得分:1)

<强> ES5

function startTimer(duration, display) {

var timer = duration;

var interval = setInterval(function() {
var minutes = parseInt(timer / 60, 10)
var seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer !== 0) {
  --timer;
} else if (timer == 0) {
  alert('Your time has been completed.');
  clearInterval(interval);
  }
}, 1000);

}

  window.onload = function() {
  var seconds = 5,
  display = document.querySelector('#time');
  startTimer(seconds, display);
};