0

I have the following tags in my html documentation:

<p id="demo1">This is my animation text</p>
<button onclick="runAnimation()">RunAnimation</button>

I have declared the following javascript code to make animation for the text in

tag:

function changeText(){
    var text = document.getElementById("demo1").innerHTML;
    text = text.substr(text.length - 1) + text.substr(0, text.length - 1);
    document.getElementById("demo1").innerHTML = text;
}

`function` runAnimation(){
    setInterval(changeText(), 300);
}

The code above didn't work, instead, when i use anonymous function, everything now OK, can anyone explain me why?

function runAnimation(){
    setInterval(function(){
        var text = document.getElementById("demo1").innerHTML;
        text = text.substr(text.length - 1) + text.substr(0, text.length - 1);
        document.getElementById("demo1").innerHTML = text;
    }, 300);
}
huy nguyen
  • 1,381
  • 2
  • 11
  • 18

1 Answers1

4

You need to pass the function itself to setInterval, e.g.:

setInterval(changeText, 300);

Instead, you've coded:

setInterval(changeText(), 300);

This calls changeText and passes the returned value (in this case, undefined) to setInterval.

A. Vidor
  • 2,502
  • 1
  • 16
  • 24