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

做~自己de王妃 提交于 2019-12-11 16:13:01

问题


Im wanting to know how to put a message in everytime 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);                
    }
}

</script> 

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

回答1:


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)




回答2:


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> 


来源:https://stackoverflow.com/questions/5083534/how-do-you-display-a-message-once-a-javascript-function-restarts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!