Javascript setInterval

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

i) means a timer of 1000 milliseconds means that the moveElement function will fire every second? In other words, after it starts, will it wait 1 second and then start it again?

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

iii) after moveElement is first run, does the new value for x (x + = 10) replace the value 0 in var x = 0? that is, it is stored outside 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; 
+7
source share
3 answers

i) Yes, at least theoretically. JavaScript (mostly) single-threaded means that it will not be exactly 1000 ms.

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

iii) x defined outside the function, so it is saved every time. Each time the function is called, x will be greater than 10. If the function x were defined inside the function, it would be 10 each time it was called.

+8
source

i) setInterval will run the moveElement function every second. if it was set Timeout, it would run it only once after 1 second.

ii) it looks like he is doing.

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

+4
source

i) This will help you understand setTimeout and setInterval: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

ii) “px” is added (this means “pixels”) to assign the actual value of the “style.left” attribute, which has a unit of “px”.

iii) Yes, it replaces the value, since var x was declared outside the function, and thus a global variable.

+3
source

All Articles