Yury Lankovskiy
Yury Lankovskiy

Reputation: 153

Rotate image by modifying css

I want to rotate two images by modifying css, like so:

document.getElementById("id").style.backgroundImage = "url('image2.png')";
document.getElementById("id").style.backgroundImage = "url('image1.png')";

However, I need to do it on function call and four times only.

I've tried using setTimeout() method, however, it doesn't seem to do the job.

This is my current code that's being initialized by a click.

var d = new Date();
var n;
var i;

function flash() {
    n = d.getTime();
    var newTime = d.getTime();
    var called = 0;
    i = 0;
    while ((newTime - n) < 2000) {
        document.getElementById("i_count").innerHTML = i;
        if (!(i % 2) && (!called)) {
            called = 1;
            setTimeout("change_1()", 250);
            i++;
            called = 0;
        } else if ((i % 2) && (!called)) {
            called = 1;
            setTimeout("change_2()", 250);
            i++;
            called = 0;
        }
        newTime = d.getTime();
    }
}

function change_1() {
    document.getElementById("id").style.backgroundImage = "url('image2.png')";
    return;
}
function change_2() {   
    document.getElementById("id").style.backgroundImage = "url('image1.png')";
    return;
}

I was trying to utilize a timer instead of count in while loop, but it blocks the page and never loads. When I was using a counter in while loop, it incremented without called change_2() meaning the counter just incremented past stop condition.

I want to do a VERY (at least it sounds like) simple task, on click action rotate images for certain period of time and STOP.

... I've tried searching the net but in the past 2 hours all I've seen is continuous rotation.

Appreciate the help!

Changed the code to the following, however, I only get one cycle. The counter increments regardless of change_1 and 2 completion.

var i;

function flash() {
    i = 0;
    while (i++ < 10) {
        document.getElementById("i_count").innerHTML = i;
        setTimeout("change_1()", 250);
    }
};

function change_1() {
    document.getElementById("1").style.backgroundImage = "url('images/img_1.png')";
    setTimeout("change_2()", 250);
};

function change_2() {
    document.getElementById("1").style.backgroundImage = "url('images/img_2.png')";
};

Upvotes: 0

Views: 189

Answers (1)

Michael Lorton
Michael Lorton

Reputation: 44436

Yeah, you're not even close.

You don't invoke the timeout again and again in a loop. change_1 should set a timeout to invoke change_2, and vice versa, with a counter to stop after four.

Upvotes: 1

Related Questions