Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setInterval

This is an example from a tutorial about setInterval, but it doesn`t explain it sufficiently for my newbie brain. I would appreciate if you could answer these questions

i) does the 1000 millesecond timer mean that moveElement function will be triggered every second? In other words, after it has run, it will wait 1 second and then run it again?

ii) is the purpose of moveElement to move the "redBox" 10 pixels to the left each time it runs? is that why "px" is used in the function

iii) after moveElement runs for the first time, does the new value for x (x+=10) replace the value of 0 in var x=0? i.e. does it get stored outside of the function in the variable x at the top of the program?

var x = 0;
setInterval(moveElement,1000);

function moveElement() {
  x+=10;
  var left = x + "px";
  document.getElementById("redbox").style.left=left;
like image 963
mjmitche Avatar asked Mar 01 '11 05:03

mjmitche


2 Answers

i) Yes, at least in theory. JavaScript's (mostly) single threaded nature mean it won't be exactly 1000ms.

ii) It moves it 10px to the right, by adding 10px to the left. Px is short for pixels, which is short for picture elements.

iii) x is defined outside of the function, so it persists each time. Every time the function is called, x will be 10 larger. Had x been defined within the function, it will be 10 each time it is called.

like image 55
alex Avatar answered Sep 18 '22 17:09

alex


i) the setInterval will run the moveElement function every second. if it were setTimeout it would only run it once after 1 second.

ii) seems like thats what it does.

iii) in this case x is not declared anywhere in the function moveElement so then it tries to find a global variable which it does at the top. So yes it will store the new value in the x outside of the function.

like image 45
Timothy Ruhle Avatar answered Sep 22 '22 17:09

Timothy Ruhle