开发者

how to stop a message from a javascript timer from repeating?

I have a timer for my game, but the mess开发者_如何学JAVAage will keep going on the mage, so it says it multiple times, i was wondering how you can get it to say it once.

<head>
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;

function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == -1||c < -1){
        var _message = document.createTextNode("You have mined 1 iron ore!");
document.getElementById('message').appendChild(_message); 
startover();
}
}

function startover() {
 c = 10;
clearTimeout(t);
timer_is_on=0;
doMining();
}
function doMining() {
if (!timer_is_on) {
    timer_is_on = true;
    t = setInterval(function () {
        timedCount();
    }, 1000);                
}
}

</script> 

<SPAN STYLE="float:left">
<form>
<input type="button" value="Mining" onClick="doMining()">
<input type="text" id="txt">
</form>
</SPAN>
<html>
<center>
<div id='message'></div>


Instead of setInterval use window.setTimeout.

This will trigger the function only once.

Edit: if you mean you want one message to appear and update every time, first add global counter:

var mineCount = 0;

Then change the code to this:

if (c <= -1) {
    mineCount++;
    var _message = "You have mined " + mineCount + " iron ore" + ((mineCount > 1) ? "s" : "") + "!";
    document.getElementById('message').innerHTML = _message;
    startover();
}

This will assign the contents of the element instead of adding to it each time.


Your startOver function calls doMining(). Surely, it shouldn't...?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜