0
var t = 0;
function addDiv()
{
    var div = document.createElement("div");
    t++;
    div.setAttribute("id", "box" + t);
    document.body.appendChild(div);
    AddStyle();
}

var h = 0;
var p = 1;    
function doMove()
{
    var okj = document.getElementById("box" + p);

    if (p <= t) {
        p++; 
    }
    var g = setInterval(function () {
        var go = parseInt(okj.style.left, 0) + 1 + "px";
        okj.style.left = go;
    }, 1000 / 60);
}

My question is that after the p increments that is p++ will my var p = 1 be incremented everytime I call doMove? Please help me regarding this matter.

Mark Walters
  • 12,060
  • 6
  • 33
  • 48
Subramanya Rao
  • 151
  • 3
  • 6

1 Answers1

2

By definition global variables have global scope, so you can increment them or re-assign them within a function and that will work, how fantastic is that!

Although as Borgtex has pointed out your if statement won't work

if (p <= t) {
   p++; 
}

You have declared the variable t in another function so your doMove() function does not have access to it, therefore this statement will always return false; If you make t a global variable or pass it into your doMove() function as a parameter then this will work.

var p = 1; // this variable is global

function varTest(){
   p++ //This will work because p is global so this function has access to it.
   var t = 0;
}

function anotherTest(){
   if(p<t){   //This will return false - t is not in scope as it was defined in another function
      alert("supercalifragilisticexpihalitoscious"); 
   }
}
Mark Walters
  • 12,060
  • 6
  • 33
  • 48
  • @Connor My bad, it was a long time ago when I last saw it and my memory of the film is a bit skewed. Thank you for the correction, I shall never make this mistake again. – Mark Walters Jul 22 '13 at 07:54