Dgameman1
Dgameman1

Reputation: 378

clearInterval not working in Javascript

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

Upvotes: 1

Views: 3942

Answers (2)

Spaceman
Spaceman

Reputation: 1339

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);
    }
}

Upvotes: 3

Shomz
Shomz

Reputation: 37701

Your 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.

Upvotes: 8

Related Questions