# Efficient text scroller

I wrote this small test, i would love to know if it's possible to achieve the same result in a more "efficient" way, before any moderator closes this question, it's not subjective because my defention of efficient here means less lines of code, and less memory usage.

Here is a Demo : http://jsfiddle.net/YsjLp/

and here is the JS code :

var position = 0;
var divToEdit = document.getElementById('here');

function executeIt(){
setInterval(function(){moveIt()},300);
}

function moveIt(){
var textToInsert = '';
var textLength = 10;

for (var i = 0; i <= textLength; i++) {

if(i == position){
textToInsert += '[-]';
}else{
textToInsert += '-';
}
};

if(position == textLength){
position = 0;
}else{
position += 1;
}

divToEdit.innerHTML = textToInsert;
}

executeIt();


## migrated from stackoverflow.comSep 18 '13 at 14:33

This question came from our site for professional and enthusiast programmers.

• Is there even a question here? – user25057 Sep 4 '13 at 5:36
• @remyabel yes, the question is, could the above code be rewritten in a more efficient way, efficient defined in the question body. – Taleb Elem Sep 4 '13 at 5:38

As you define efficient to be "less lines of code", here it is:

function moveIt(){
var textToInsert = '';
var textLength = 10;

for (var i = 0; i <= textLength; i++)
textToInsert+= (i==position)?'[-]':'-';
(position==textLength)?position=0:position++;
divToEdit.innerHTML = textToInsert;
}

• Fair enough, a good use of ternary operators, i would love to see both benchmarked, i'll check and see, thank you. – Taleb Elem Sep 4 '13 at 21:07