2

我的游戏有一个计时器,但消息会一直传到法师上,所以它会说多次,我想知道你怎么能让它说一次。

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

2 回答 2

2

而不是setInterval使用window.setTimeout.

这只会触发该功能一次。

编辑:如果您的意思是您希望每次都出现并更新一条消息,请首先添加全局计数器:

var mineCount = 0;

然后把代码改成这样:

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

这将分配元素的内容,而不是每次都添加。

于 2011-02-23T08:20:54.783 回答
0

您的startOver函数调用doMining(). 应该不会吧……?

于 2011-02-23T08:21:51.910 回答