Edit in JSFiddle

var d = document.getElementById('sample');
var cDiv = document.getElementById('counter');
var counter = 0;
var margin = 0;
var increment = 1;
function updateLocation(){
    counter++;
    if(Math.floor(counter / 100) % 2 == 0){ 
        margin += increment;
    }
    else{
        margin -= increment;       
    }
    d.style.marginLeft = margin + "px";
    cDiv.innerHTML = counter;
    cDiv.style.marginLeft =  150 - margin + "px";
    if(counter >1000){
        counter = 0;
    }
}
var myInterval = setInterval( updateLocation, 10);
<div id='sample'>hello</div>
<div id ='counter'></div>
div{
    background-color:red;
    height:50px;
    width:50px;
}
#counter{
    margin-left:150px;
}