我有一个变量的实时更新程序,但它不断崩溃浏览器,我可以在Javascript中做一个实时更新程序的任何其他方法非常感谢!
这是我的代码;
var health;
function decrease() {
health = health - 2;
}
function mainUI() {
setInterval(decrease(),30000);
if (health <= 5) {
document.write("Below 5!");
} else {
document.write("Over 5!");
}
}
mainUI();
setInterval(mainUI(),1000);
它的整个想法是刷新可变数据而不刷新浏览器,有什么建议吗?
答案 0 :(得分:1)
你可以这样做:
HTML
<body>
<span id="spanHealth"></span>
</body>
使用Javascript:
var health;
function decrease() {
health = health - 2;
}
function mainUI() {
var msg = (health <= 5 ? "Below 5!" : "Over 5!");
document.getElementById("spanHealth").innerHTML = msg;
}
setInterval(mainUI, 1000);
setInterval(decrease, 30000);
答案 1 :(得分:0)
这是一个小页面,可以使用div
setInterval
的按钮
<强>风格强>
#health{
width: 170px;
}
.normalHealth{
color: white;
background-color: green;
}
.lowHealth{
color: white;
background-color: red;
}
.dead{
color: white;
background-color: black;
}
<强>脚本强>
var health = 10;
var poisonTimer;
var healthDiv;
function loseHealth() {
health -= 2;
updateUI();
}
function givePoison() {
poisonTimer = setInterval(loseHealth, 1000);
}
function giveAntidote() {
clearInterval(poisonTimer);
}
function kill() {
health = 0;
healthDiv.className = "dead";
giveAntidote(healthDiv);
document.getElementById("revive").disabled = false;
updateUI();
}
function revive() {
health = 10;
healthDiv.className = "normalHealth";
document.getElementById("revive").disabled = false;
updateUI();
}
function updateUI() {
healthDiv.innerHTML = health;
if (health > 4) {
healthDiv.className = "normalHealth";
}
else if (health > 0) {
healthDiv.className = "lowHealth";
}
else {
kill();
}
}
function main() {
healthDiv = document.getElementById("health");
document.getElementById("poison").addEventListener("click", givePoison);
document.getElementById("cure").addEventListener("click", giveAntidote);
document.getElementById("revive").addEventListener("click", revive);
}
window.onload = main;
<强> HTML 强>
<html>
<head>
<title>Health Bar</title>
</head>
<body>
<div id="health" class="normalHealth">10</div>
<button id="poison">Poison</button>
<button id="cure">Cure</button>
<button id="revive" disabled>Revive</button>
</body>
</html>