Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference between fadeIn() delay() and fadeOut()

I am trying to calculate the time difference from the moment the command line (3) starts and ends, but looks like I am wrong, as line(7) shows zero. I am expecting it to show 6500 (1500 + 3500 + 1500). please help me.

sd = new Date(); 
sdm = sd.getMilliseconds();
$(imgs).eq(i).fadeIn(1500).delay(3500).fadeOut(1500);
ed = new Date(); 
edm = ed.getMilliseconds();
df = edm - sdm;
document.getElementById('df').innerHTML = df;

The reason I am throwing this question is, I am writing a slideshow (very simple) and it is not showing the images in sequence properly as it jumps from one to another.

This is my HTML and the JS.

    $(document).ready(
      function() {

            var i=0;
            var imgs = $('#images ul').children();
            var j = imgs.length;

            setInterval(function(){ runIt(); }, 6500);

            function runIt() {
                i = i + 1;
                if (i == j) { i=0;}

                $(imgs).eq(i).fadeIn(1500).delay(3500).fadeOut(1500);
            }

    }); 

<div id="slider">
    <ul>
        <li><img src="images/slider/s1.jpg" /></li>
        <li><img src="images/slider/s2.jpg" /></li>
        <li><img src="images/slider/s3.jpg" /></li>
        <li><img src="images/slider/s4.jpg" /></li>
    </ul>   
</div>

thank you.

like image 207
Isaac Avatar asked Feb 05 '16 19:02

Isaac


1 Answers

Calls to animating functions in jQuery are asynchronous. You need to use a callback function, like so:

$(element).fadeOut(delay,
    function() {
        // callback action
    }
);

However, this will not work as expected. getMilliseconds returns the milliseconds that have passed since the beginning of the second, e.g., if the current time is 20:18:20.430, it will return 430. You want to use the method getTime instead. It returns the number of milliseconds since the Unix Epoch.

Since you are using jQuery, instead of document.getElementById'ing, you can use the much more concise $('#id').html('...');. This leaves us with:

sd = new Date(); 
sdm = sd.getTime();
$(imgs).eq(i).fadeIn(1500).delay(3500).fadeOut(1500,
    function() {
        ed = new Date(); 
        edm = ed.getTime();
        df = edm - sdm;
        $('#df').html(df);
    }
);

Your slideshow is probably also messed up because of this.

A small nitpick regarding your second snippet: in var imgs = $('#images ul').children();, the .children() method returns a jQuery object. You needn't really run it through $() again, but you can if you think that's more clear.

imgs.eq(i).fadeIn(1500).delay(3500).fadeOut(1500);
like image 83
Midgard Avatar answered Oct 06 '22 00:10

Midgard