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;
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)
xis defined outside of the function, so it persists each time. Every time the function is called,xwill be 10 larger. Hadxbeen defined within the function, it will be 10 each time it is called.