admin管理员组文章数量:1335583
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);
}
}
本文标签: clearInterval not working in JavascriptStack Overflow
版权声明:本文标题:clearInterval not working in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742384087a2464677.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论