This is the code I have so far
<div>
<img src="robot.png" id="robotPic">
</div>
<br />
<br />
<input type="button" name="Start" value="Start" id="Start" onclick="moveImage();">
<script type="text/javascript">
var moving = false;
var screenWidth = window.innerWidth;
var i = 0;
function moveImage() {
if (!moving) {
moving = true;
var robotMoving = setInterval(function() {
document.getElementById("robotPic").style.paddingLeft = i + "px";
i = i + 10;
}, 500);
} else {
clearInterval(robotMoving);
}
}
</script>
For whatever reason, the robotPic
doesn't stop moving when I click the Start
button again for some reason and I don't understabd
This is the code I have so far
<div>
<img src="robot.png" id="robotPic">
</div>
<br />
<br />
<input type="button" name="Start" value="Start" id="Start" onclick="moveImage();">
<script type="text/javascript">
var moving = false;
var screenWidth = window.innerWidth;
var i = 0;
function moveImage() {
if (!moving) {
moving = true;
var robotMoving = setInterval(function() {
document.getElementById("robotPic").style.paddingLeft = i + "px";
i = i + 10;
}, 500);
} else {
clearInterval(robotMoving);
}
}
</script>
For whatever reason, the robotPic
doesn't stop moving when I click the Start
button again for some reason and I don't understabd
- 1 robotMoving is local to the function. When you call moveImage a second time, it's a different instance of the function and robotMoving variable. Simple fix is to make robotMoving global (but there are better ways). – RobG Commented May 16, 2016 at 3:25
- 1 @Spaceman: Not setting it back to false does not at all explain why the robot never stops moving. It might explain the UNASKED QUESTION of why the robot cannot move more than once. – slebetman Commented May 16, 2016 at 3:29
- @slebetman your correct I think my mind just jumped to conclusions there. apologies I messed up. Robg is correct entirely. – Spaceman Commented May 16, 2016 at 3:32
2 Answers
Reset to default 8Your interval reference robotMoving
lives only inside that function scope. Which means it's set to undefined every time you run that function (and you're running it multiple times). To fix it, move the variable robotMoving
outside of that function, and just modify its value from the inside.
Your interval is out of scope.
Perhaps add try this.
Shomz has a good explination in his awnser as to whats happening.
var moving = false,
screenWidth = window.innerWidth,
i = 0,
interval;
function moveImage() {
if (!moving) {
moving = true;
interval = setInterval(function() {
document.getElementById("robotPic").style.paddingLeft = i + "px";
i = i + 10;
}, 500);
} else {
clearInterval(interval);
}
}