benji_r
benji_r

Reputation: 555

JavaScript SetInterval () is not working after clicking

Hi I have wrote this code and it suppose to move the object every 3000 ms after clicking on the object, but some how the time its not working, can anyone tell me what I am doing wrong, I am just learning javascript; thank you very much

function move1() {
    var im1 = document.images[0];
    im1.onclick = function() {
        im1.style.left = parseInt(im1.style.left) + 1 + "px";
    }
}

function move2() {
    var im2 = document.images[1];
    im2.onclick = function() {
        im2.style.left = parseInt(im2.style.left) + 10 + "px";
    }
}

window.onload = function() {
    setInterval(move1, 100);
    setInterval(move2, 3000);
}

Upvotes: 0

Views: 322

Answers (2)

Bergi
Bergi

Reputation: 664307

You're doing it the other way round. Every 3000ms you make it possible to move the image by 1px when clicking on it.

function move(el, ms, px) {
/* moves the el every ms by px
returns the interval id to clear the movement */
    return setInterval(function() {
        el.style.left = parseInt(el.style.left) + px + "px";
    }, ms);
}
window.onload = function() {
    var im0 = document.images[0];
    var im1 = document.images[1];
    im0.onclick = function() {
        move(im0, 100, 1);
    };
    im1.onclick = function() {
        move(im1, 3000, 10);
    };
}

Upvotes: 2

Charles Ma
Charles Ma

Reputation: 49141

Your move function registers the image on click, but doesn't actually do any moving until the user clicks. What you want is more like this:

function move1() {
    var im1 = document.images[0];
    im1.style.left = parseInt(im1.style.left) + 1 + "px";
}

function move2() {
    var im2 = document.images[1];
    im2.style.left = parseInt(im2.style.left) + 10 + "px";
}

window.onload = function() {
    var im2 = document.images[1];
    im2.onclick = function() {
        setInterval(move2, 3000);
    }

    im1.onclick = function() {
        setInterval(move1, 100);
    }
}

Upvotes: 0

Related Questions