Lucian Tarna
Lucian Tarna

Reputation: 1827

JavaScript Timing

I want to select all the elements of a class. Then change that class to another class . After 0.5 seconds i want to revert the elements back to their original class. I must do this 8 times in a row. Even though my code achieves that(in a way) i can't see the color changes in the buttons . Can anyone help me ? it's a timing problem i guess. Here is the js code :

$(document).ready(function(){
    $('#start').click(function(){
        game();
    })

    function game(){
        var ordine = new Array();
        for(var t = 1; t <= 8; t++){
            var y = 0;
            for (var k = 0; k < t; k++) {
                var x = Math.floor((Math.random() * 4) + 1);
                ordine[y++] = x;
                change1(x);
                setTimeout(change2(x), 500);
            }
        }
    }

    function change1(y){
        var z = 'cls' + y;
        var t = 'cls' + y + 2;
        $("." + z).removeClass(z).addClass(t);
    }

    function change2(y){
        var z = 'cls' + y + 2;
        var t = 'cls' + y;
        $("." + z).removeClass(z).addClass(t);
    }
})

Here you can find the full code(html,css and js) http://jsfiddle.net/Cx5VK/2/

Upvotes: 0

Views: 74

Answers (1)

UweB
UweB

Reputation: 4110

The problem is in the following line:

setTimeout(change2(x), 500);

You are calling the function change2 here, passing its return value to setTimeout. What you actually want though is to call the change2 function after 500ms. Change your code to:

setTimeout(function() { change2(x); }, 500);

That way, you are passing an anonymous function to setTimout, which will then be executed by it after 500ms.

EDIT: I've modified your JSFiddle: http://jsfiddle.net/Cx5VK/7/ stripping out a lot of code that didn't do anything in that sample (you quite possibly need it elsewhere):

$(document).ready(function () {
    $('#start').click(function () {
        game();
    })

    function game() {
        var x = Math.floor((Math.random() * 4) + 1);
        change1(x);
    }

    function change1(y) {
        var z = 'cls' + y;
        var t = 'cls' + y + 2;
        $("." + z).removeClass(z).addClass(t);
        setTimeout(function() { change2(y); }, 500);
    }

    function change2(y) {
        var z = 'cls' + y + 2;
        var t = 'cls' + y;
        $("." + z).removeClass(z).addClass(t);
        game();
    }
});

Now, the game function simply gets a random number and calls change1 with that number as parameter. change1 itself will set the timeout to reset the color for that square via change2. At the end of that function, the game is "restarted" by a simple call to game(), to get another random number and so on and so forth. I hope this is what you were looking for.

Upvotes: 5

Related Questions