-->

How can use the setInterval() to change the text?

2019-07-31 08:36发布

问题:

I've been working at this for quite some time now. I'm trying to create a simple timer that counts down. I've gotten the alert() to work, but unfortunately the textToChange does not change. I've reproduced a copy of my code below. Any help would be greatly appreciated! Thank you.

<script type="text/javascript">
    var timeLeft = 0;
    var changingTextElement;
    var changingText = new Array();
    var ctr = 0;

    function timeMsg(thing)
    {
    var length = thing.inputbox.value*1000;
    var t = setTimeout("alertMsg()",length);
    timeLeft = length/1000;
    initChangeText();
    }

    function alertMsg()
    {
    alert("Alert!");
    }

    function initChangeText(){
        changingTextElement = document.getElementById("textToChange");
        changingText[ctr] = changingTextElement.innerHTML;
        ctr++;
        while(timeLeft > 0){
            changingText[ctr] = timeLeft;
            timeLeft--;
            ctr++;
        }
        ctr = 0;    
        setInterval("changingText()",1000);
    }

    function changingText() {
        ctr++;
        if(ctr >= changingText.length){
            changingTextElement.innerHTML = 0;
        }
        else{
            changingTextElement.innerHTML = changingText[ctr];
        }
    }

</script>

回答1:

You are using a changingText function and a changingText array ...

See the conflict ?


As additional info,

do not use strings as name functions in the setInterval method. Use a reference to the method directly

setInterval(changingText, 1000);


回答2:

For a simple countdown timer, this code is too big. Basically, what you should be doing is:

  • Set the number of seconds from which should be counted down
  • Start a timer using setInterval which decrements the counter and displays it

That can be simple as:

var countFrom;
var timer;
function run_timer() {
    document.getElementById("textToChange").innerHTML = --countFrom;
    // !0 evaluates to true, if the counter reaches 0 (wait 0 seconds) ...
    if (!countFrom) {
        clearInterval(timer);
        alert("Timer finished!");
    }
}
function init_timer () {
    // stop previous timers if any
    clearInterval(timer);
    // start counting from 30 seconds
    countFrom = 30;
    timer = setInterval(run_timer, 1000);
}


回答3:

Your version in a fiddle. I changed the function name

http://jsfiddle.net/mplungjan/jqeDv/