user4075837
user4075837

Reputation:

How do you prevent horizontal interfearing of JS movement?

I'm working on a school project, we have just started learning JavaScript. I have to make a script that makes something move with JS. Well, I made the following script:

var object = document.getElementById("object");
        var omhoog = document.getElementById("omhoog");
        var omlaag = document.getElementById("omlaag");
        var links = document.getElementById("links");
        var rechts = document.getElementById("rechts");

        object.style.left = '0px';
        object.style.top = '0px';

        omlaag.onclick = function()
        {
            var positiehuidigtop = parseInt(object.style.top);
            setInterval(function()
            {
                if (parseInt(object.style.top)<positiehuidigtop+100)
                {
                    object.style.top = (parseInt(object.style.top) + 10) + 'px';
                }
            }, 10);
        }

        links.onclick = function()
        {
            var positiehuidigleft = parseInt(object.style.left);
            setInterval(function()
            {
                if (parseInt(object.style.left)>positiehuidigleft-100)
                {
                    object.style.left = (parseInt(object.style.left) - 10) + 'px';
                }
            }, 10);
        }

        rechts.onclick = function()
        {
            var positiehuidigleft = parseInt(object.style.left);
            setInterval(function()
            {
                if (parseInt(object.style.left)<positiehuidigleft+100)
                {
                    object.style.left = (parseInt(object.style.left) + 10) + 'px';
                }
            }, 10);
        }

Sorry for the Dutch stuff in there, but it's variables, so the name doesn't really matter.

Anyways, at first I just had the part of the script that made the div move right. Worked like a charm. But when I started adding left, it would interfear. Both directions are sort of fighting.

I really don't know what to do and this stuff is getting my a headache :/

Upvotes: 1

Views: 40

Answers (1)

huysentruitw
huysentruitw

Reputation: 28091

You should use clearInterval to stop the already running interval timer before starting the new one.

var currentInterval;

omlaag.onclick = function() {
    clearInterval(currentInterval);
    currentInterval = setInterval(
        ...
    );
};

rechts.onclick = function() {
    clearInterval(currentInterval);
    currentInterval = setInterval(
        ...
    );
};

Upvotes: 1

Related Questions