jq beginner
jq beginner

Reputation: 1070

how to delay a function works without a trigger (with document ready)

i have this function that starts a slideshow automatically and i need to delay it till the server executes query and echo data

 $(document).ready(function(){

        $('#camera_wrap_2').camera({
            height: '380px',
            loader: 'bar',
            pagination: false,
            thumbnails: true
        });

    });

i've tried this but didn't work

        $(document).ready(function(){
        setTimeout(camera,2000);

    });
    $('#camera_wrap_2').camera({
            height: '380px',
            loader: 'bar',
            pagination: false,
            thumbnails: true
        });

Upvotes: 1

Views: 3364

Answers (3)

MatRt
MatRt

Reputation: 3534

You can also use the delay() jQuery function

$(document).ready(function(){

    $('#camera_wrap_2').delay(2000).camera({
        height: '380px',
        loader: 'bar',
        pagination: false,
        thumbnails: true
    });

});

Upvotes: -1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

If with

server executes query

you mean some ajax call then you need to use the callback and call your code there.

Otherwise, in the timeout example, you need to create a function named camera because that is what setTimeout expects

$(document).ready(function(){
    setTimeout(camera,2000);
});
function camera(){
    $('#camera_wrap_2').camera({
            height: '380px',
            loader: 'bar',
            pagination: false,
            thumbnails: true
    });
}

Upvotes: 3

jfriend00
jfriend00

Reputation: 707356

If what you're trying to do is run the .camera method after a delay of 2 seconds, you can do that like this by putting the method into a function that setTimeout() will call after the prescribed delay:

$(document).ready(function(){
    setTimeout(function() {
        $('#camera_wrap_2').camera({
            height: '380px',
            loader: 'bar',
            pagination: false,
            thumbnails: true
        });
    },2000);
});

Usually a hard-coded wait time like this is the wrong solution. The right solution is usually to wait for a particular event to occur and have a listener for that event.

I can't tell from your question (since you included no information on what the server response was that you are waiting for), but perhaps the event you want here is the response from an ajax call to the server. If that is the case, then you can install a callback for the completion of that ajax call and run the .camera() method in that callback.

Upvotes: 1

Related Questions