首页 > 解决方案 > 如何使用重复功能重置所有内容并重新运行所有内容?

问题描述

我有一个在按钮单击事件上运行的重复功能,但是它不能正常工作。也许是因为有太多的 setIntervals 正在运行,尽管我试图清除它们。我还确保将使用的变量重置为其初始值,但是当按下再次拍摄按钮时,移动的圆圈一直显示褪色,所以我假设 setInterval 有问题,但是,我不知道它是什么。它也不再画篮球了。

var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;

var ctx = canvas.getContext("2d");

var intervalId2;
var intervalId1;

//Initializing Variables

var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;

var resetVars = function() {

  dt = 0.01;
  var x = r + 1;
  var y = 500 / 1.2;
  var xc = 145;
  var yc = 300;
  var dxc = 95;
  var dyc = 300;
  var theta = 0;
};

//resetVars();

var reset = function() {
  ctx.clearRect(0, 0, 800, 800);
  drawHoop()
};
   
  

//Interval Id to eventually clear it to stop this to shoot

var intervalID = setInterval(moveCirc, 10000 * dt);

var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
  if (dxc <= 110 && shoot1.keyCode == 32) {
    console.log(dxc);
    clearInterval(intervalID);
    make();
    count = count + 1;
    document.getElementById("count").innerHTML = "You've made " + count + "  baskets.";
  }

  if (dxc > 110 && shoot1.keyCode == 32) {
    console.log(dxc);
    clearInterval(intervalID);
    miss();
    document.getElementById("count").innerHTML = "You've made " + count + "  baskets.";
  }
};

var repeat = function() {
  reset();
  clearInterval(intervalID);
  clearInterval(intervalId2);
  clearInterval(intervalId1);
  resetVars();
  drawBasketball();
  drawHoop();
  moveCirc();
  intervalID = setInterval(moveCirc, 10000 * dt);


  document.body.onkeyup = function(shoot1) {
    if (dxc <= 110 && shoot1.keyCode == 32) {
      console.log(dxc);
      clearInterval(intervalID);
      make();
      count = count + 1;
      document.getElementById("count").innerHTML = "You've made " + count + "  baskets.";
    }

    if (dxc > 110 && shoot1.keyCode == 32) {
      console.log(dxc);
      clearInterval(intervalID);
      miss();
      document.getElementById("count").innerHTML = "You've made " + count + "  baskets.";
    }
  };
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>

<body style="background-color:powderblue;">

  
  <p id="count"></p>
  <button id="again" onclick="repeat()"> Shoot Again </button>

</body>

标签: javascript

解决方案


这应该为重复功能制作一个停止按钮

<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>

推荐阅读