hei
hei

Reputation: 109

how to use clearInterval() properly?

I want to use buttons to make a change of position continuously of an object in four direction (up,down,left and right) by one click. When I click one direction button, then clicking on the 'pause' button, the object will stop moving (this works). But when I clicked more than once of direction button without giving 'pause' button, all movements happened in this object (e.g. the x times of 'up' clicked, the x times of moving speed will be), even 'pause' button applies, only one movement will stop.

<script>
var pause=false;
var change;
function move(event) {
    pause=false;
    console.log('start')

    var objId=event.id;
    var objStyle=document.getElementById('object');

    change=setInterval(function () {
            if (objId==='up'){
                objStyle.style.top=parseInt(objStyle.style.top)-10+'px';
            }
            else if (objId==='down'){
                objStyle.style.top=parseInt(objStyle.style.top)+10+'px';
                console.log('down')
            }
            else if (objId==='left'){
                objStyle.style.left=parseInt(objStyle.style.left)-10+'px';
            }
            else if (objId==='right'){
                objStyle.style.left=parseInt(objStyle.style.left)+10+'px';
                console.log('right')
            }



    },100)


}

function Pause() {
    clearInterval(change)
}

Upvotes: 1

Views: 73

Answers (1)

Willis Zhang
Willis Zhang

Reputation: 109

What result do you expect?

The reason is each time you click the button, the "change" variable was re-assigned to a new interval ID value because a new timeout was created (eg. click two buttons before pause and two intervals are running!). So when you click the "pause" button, only the timeout corresponding to the last "change" ID will be cleared.

If you want to only move one direction upon a time, then you need to first "clearInterval" when you click the move button, and then setInterval to the new direction.

Upvotes: 2

Related Questions