javascript - 如何使用重复功能重置所有内容并重新运行所有内容?
问题描述
我有一个在按钮单击事件上运行的重复功能,但是它不能正常工作。也许是因为有太多的 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>
解决方案
这应该为重复功能制作一个停止按钮
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>
推荐阅读
- git - 为什么有些提交不属于任何分支?
- java - 在java的堆空间中创建的对象如何具有全局访问权限?
- javascript - 分配一个字符串但取回一个对象 - 浏览器在玩吗?
- java - How to overwrite a jar file in a maven generated war?
- swift - Firestore 按时间排序,但按 ID 排序
- php - insert key/value pair into an array with two level
- java - 在 Java 中如何计算一系列数字以找到乘积,即传递给使用可变长度参数列表的方法
- asp.net - JSON 列表不使用 Distinct 命令删除重复项
- jsp - 同一个jsp上的两个下拉列表返回null
- c# - 使用 ARBCreateSubscriptionRequest 验证信用卡或借记卡,例如 Customer Profile 的 validationMode 字段