我的实时更新程序崩溃了浏览器

时间:2014-01-07 15:52:05

标签: javascript function variables setinterval

我有一个变量的实时更新程序,但它不断崩溃浏览器,我可以在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);

它的整个想法是刷新可变数据而不刷新浏览器,有什么建议吗?

2 个答案:

答案 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的按钮

enter image description here

<强>风格

 #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>