Search code examples
javascriptjquerydelay

jquery delay function


My delay function is not working in my jquery rotate function. I am not sure why.

Basically, my code will make my div turn an angle and it will stop at a certain angle. This works at the moment. However i added a delay so it it will work after 3 or 4 seconds.

However its not doing it.

$(window).load(function() {
    var $elie = $("#super");
    rotate(1);

    function rotate(degree) {
        $elie.css({
            '-webkit-transform': 'rotate(' + degree + 'deg)',
            '-moz-transform': 'rotate(' + degree + 'deg)',
            '-o-transform': 'rotate(' + degree + 'deg)',
            '-ms-transform': 'rotate(' + degree + 'deg)',
            'transform': 'rotate(' + degree + 'deg)'
        });
        console.log(degree);
        if (degree < 55) {
            timer = setTimeout(function() {
                rotate(++degree)
            }, 10)
            delay: 4000;
        }
    }
});​

Solution

  • If you want to delay the rotation just make a 'setTimeout' around the delay function:

    $(window).load(function() {
        var $elie = $("#super");
        setTimeout(function() {
            rotate(1);
        }, 4000)
    
        function rotate(degree) {
            $elie.css({
                '-webkit-transform': 'rotate(' + degree + 'deg)',
                '-moz-transform': 'rotate(' + degree + 'deg)',
                '-o-transform': 'rotate(' + degree + 'deg)',
                '-ms-transform': 'rotate(' + degree + 'deg)',
                'transform': 'rotate(' + degree + 'deg)'
            });
            console.log(degree);
            if (degree < 55) {
                timer = setTimeout(function() {
                    rotate(++degree)
                }, 10)
            }
        };
    });​
    

    (also as mentioned removed the dalay: 4000, which don't has the effect you want!)

    Fiddler example: http://jsfiddle.net/49VEe/

    edit2:

    You can use HTML5 transition to get the rotation effect instead of your recursive function (sample without delay:

    $(window).load(function() {
        var $elie = $("#super");
            rotate(55);
    
        function rotate(degree) {
            $elie.css({
                '-webkit-transform': 'rotate(' + degree + 'deg)',
                '-moz-transform': 'rotate(' + degree + 'deg)',
                '-o-transform': 'rotate(' + degree + 'deg)',
                '-ms-transform': 'rotate(' + degree + 'deg)',
                'transform': 'rotate(' + degree + 'deg)',
                '-webkit-transition': 'all 1s ease-in-out',
                '-moz-transition': 'all 1s ease-in-out',
                '-o-transition': 'all 1s ease-in-out',
                transition: 'all 1s ease-in-out'
            });
        };
    });​
    

    Fiddler: http://jsfiddle.net/mZzjP/