如何在单击停止按钮后停止执行javascript?

时间:2017-10-01 16:47:34

标签: javascript jquery

    <script>
function timer(duration, elementId, scoreID, mistakesID){
  var start = Date.now();
  var min, sec, diff;
  var scoreComputed = false;

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

    min = ( diff / 60 ) | 0;
    sec = ( diff % 60 ) | 0;

    //If less than 10, add zero in front of it to keep tens place
    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;

    elementId.textContent = min + ":" + sec;

    if ( diff <= 0 ){
      elementId.textContent = "0:00";

      if (!scoreComputed){
        score /= (duration / 60);
        score = Math.round(score);
        scoreComputed = true;
      }

      scoreID.textContent = score;
      document.getElementById("usertext").readOnly = true;

      $("#resultsContainer").fadeIn(1500);

      if(mistakes.length > 0){
        var mistakesStr = "";

        for(var i = 0; i < mistakes.length; i++){
          mistakesStr += i > 0 ? ", " : "";
          usertextArr[mistakes[i]] = usertextArr[mistakes[i]] === "" ? "blank" : usertextArr[mistakes[i]];
          mistakesStr += usertextArr[mistakes[i]] + " instead of " + textArr[mistakes[i]];;
        }
        mistakesID.textContent = mistakesStr;
        $("#mistakesContainer").fadeIn(1500);
         $('.type-test-wrapper').css("filter","blur(3px)");
      }
      return;
    }
  };
  timerCompute();
  setInterval(timerCompute, 1000);
}

var timerStarted = false;
$('#usertext').on('keydown', function() {

  var time = 60 * 0.1,
  display = document.querySelector('#time');
  scoreDisplay = document.querySelector('#score');
  mistakesDisplay = document.querySelector('#mistakes');
  if ( timerStarted === false ){
    timer(time, display, scoreDisplay, mistakesDisplay);
    typeTest();
    timerStarted = true;
  }
});
</script>

以上脚本来自打字测试。当打字测试结束时,上面的脚本在结果框中淡出。我试图修改代码。我想在结果框中添加一个关闭按钮,以便用户在查看结果后可以关闭该框。所以我添加了以下代码来关闭结果框。

<script type='text/javascript'>
jQuery(document).ready(function($){
$('.close-btn, body').click(function(){
$('.type-test-wrapper').css("filter","blur(0px)");
$('#resultsContainer, #mistakesContainer').stop().fadeOut('medium');
});

});
</script>

我面临的问题是,当我点击关闭按钮时,框会淡出#resultContainer, #mistakesContainer但是一旦框变淡,它就会逐渐消失。无论我关闭框多少次,它一次又一次地消失。我希望一旦用户点击关闭按钮,该框就不应再次显示。如何修复代码,以便一旦框淡出,第一个代码不再在框中淡出。我是javascript的新手。谢谢你的帮助。

此处的实时网页https://htmlpreview.github.io/?https://raw.githubusercontent.com/dp121112/type-testing/master/test.html

1 个答案:

答案 0 :(得分:1)

我认为你没有清除间隔 尝试按如下方式确定间隔。

var intrvl= setInterval(timerCompute, 1000); 

并在完成后清除它

scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
clearInterval(intrvl);