Jed
Jed

Reputation: 13

How to wrap script in setTimeout

I have some jquery code which resets image sliders to slide 1 when the tabs are clicked. The problem is, it happens instantly, so you see a little flicker of the reset slider before the tab fades out.

I want to "hold" the reset back about half a second until it fades out.

I have been told I need to wrap the code in a "setTimeout" function, so I am hoping for some assistance on how to do this.

It is the "Work" section of this page that I'm talking about: www.oncreative.com.au

This is the code I have to reset the sliders:

<script>
    $('.reset').click(function() {
    $('.workslider').each(function() {
           var s = $(this).data('royalSlider');
           s.st.transitionSpeed = 0;
            s.goTo(0);
            setTimeout(function() {
                s.st.transitionSpeed = 600;
            }, 10); 
    });
    });
</script>

Thanks in advance!

Upvotes: 0

Views: 2918

Answers (2)

RichardTowers
RichardTowers

Reputation: 4762

Here's a very basic jsFiddle that should provide a simple example of setTimeout in action: http://jsfiddle.net/A5dQn/

In your specific case:

// First you need to wrap the code you want to be
// executed when the timeout fires in a function:
function resetSliders () {
    $('.workslider').each(function() {
        var s = $(this).data('royalSlider');
        s.st.transitionSpeed = 0;
        s.goTo(0);
        setTimeout(function() {
            s.st.transitionSpeed = 600;
        }, 10); 
    });
};

// Then simply pass in a reference to your function to the setTimeout function.
$('.reset').click(function() { window.setTimeout(resetSliders, 500); } );

Edit: Obviously you want to wrap the code that's executed on the click event in the timeout, not the attaching of the click event itself. Sorry!

Upvotes: 0

Chris Herbert
Chris Herbert

Reputation: 6295

setTimeout(function(){
 // your code here.
},500);

setTimeout takes two arguments - first is your code, second is the time (in milliseconds) to delay it.

Upvotes: 3

Related Questions