1

So I want to create a tag

that the text moving from left to right with javascript. But sometimes it took longer to move the text And when I refreshed the page, it didn't run at the time I expected

My css code
#bao{
            margin:0 auto;
            width:600px;
            min-height:100px;
        }
        #bao p{
            text-align:center;
        }
My html code
<div id="bao">
        <p id="a">
            Chúc mừng sinh nhật
        </p>
    </div>
My javascript code
abc();
        function abc(){
            var a = document.getElementById('a').innerHTML;
            var c =a;
            var b = c.slice(c.length-1,c.length)+ c.slice(0,c.length-1);
            document.getElementById('a').innerHTML=b;
            setTimeout(abc,200);
        }

So What I expected is the text will keep running with the time delay is 200 millisecond but sometimes it took longer to run

yukinon
  • 23
  • 5

1 Answers1

1

The slightly sluggish behaviour can be explained mainly by the blanks you have in your text string. These blanks are processed in the same speed as all other characters but they are invisible when they are in front of or behind the actual string.

To fix this I replace()-d the blanks by visible blanks (&nbsp;) and now the whole thing seems to run more smoothly.

I also introduced a few more changes:

  • I read the text string only once from the DOM
  • trim() it from extra blanks (add one at the end) and
  • double it.
  • then I display() it, starting from steadily increasing starting positions (c.substr((i++)%l,l))
  • display()then calls itself again after intervals of 200ms.

Edit

I just noticed from @user202729's fiddle that you want to move the text to the right. For this direction the starting position needs to be decremented with c.substr(l+(i--)%l,l) as shown below:

function display(){
 a.innerHTML=c.substr(l+(i--)%l,l).replace(/ /g,'&nbsp;');
 setTimeout(display,200)
}

var i=0, a = document.getElementById('a');
var c = a.innerHTML.trim()+' ', l=c.length; c=c+c;
display()
#bao{
            margin:0 auto;
            width:600px;
            min-height:100px;
        }
        #bao p{
            text-align:center;
        }
<div id="bao">
  <p id="a">
            Chúc mừng sinh nhật.
  </p>
</div>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43