开发者

How do you display a message once a JavaScript function restarts?

I'm wanting to know how to put a message in every time the timer starts over. And here is my code thus far:

<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 == 0)
        c = 10;

}

function doMining() {
    if (!timer_is_on) {
        timer_is_on = true;
        t = setInterval(function () {
            timedCount();
        }, 1000);                
    }
}

</开发者_JAVA技巧script> 

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


2 easy steps:

  1. Create a place for your message to show up (i.e. another web element)
  2. In your conditional, when your counter reaches 0, update the message element's value

Here's an example:

<div id='message'></div>

Then, access that element and append your message or modify your method using DOM traversal (preferably using a javascript framework such as dojo or jquery but you can also do it manually):

if (c == 0) { 
    var _message = document.createTextNode("Timer has finished!");
    document.getElementById('message').appendChild(_message); 
    c = 10;
}

Also, don't put a SPAN around a form. Try a "div" instead. Span's are meant for styling in-line document elements.

Edit: I'm assuming when you say "start over" you mean when the c = 0 or the timer has run 10 times. When it "starts over" could also mean when the method is re-called by the timer (i.e. every 1 second, in which case you'd just put the update code at the top of the function)


You are already catching this event in your "if (c == 0)". Just add the extra code you need there?

You need to better define what it means to start over. Try pulling it out into its own method so you can work with it separately.

<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 == 0) 
        startOver();
}

function startOver() {
    alert("Starting Over, Fool!");
    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> 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜