kiss my armpit
kiss my armpit

Reputation: 3519

How to repeatedly display the current time right after fadein?

The following code produces a timer that displays the current time not right after the fadein. So it looks bad. How to repeatedly display the current time right after fadein?

<!doctype html>
<html>
<head>
    <title>Exercise</title>
    <style>
        #box {
            margin-left: auto;
            margin-right: auto;
            width: auto;
            background: red;
            text-align: center;
            font-size: 170px;
        }
    </style>
</head>
<body>

    <div id="box"></div>

    <script src="jquery.js"></script>
    <script>
        $(function () {
            fadeout();
        });

        function fadein() {
            $("#box").fadeIn("500", fadeout);
            //UpdateTime();
        }
        function fadeout() {
            UpdateTime();
            $("#box").fadeOut("500", fadein);
        }

        function GetTime() {
            var now = new Date();
            var obj = {
                Hour: now.getHours(),
                Minute: now.getMinutes(),
                Second: now.getSeconds()
            };

            return obj;
        }

        function UpdateTime() {
            var box = $("#box");

            var obj = GetTime();
            if (obj.Hour < 10)
                obj.Hour = "0" + obj.Hour;
            if (obj.Minute < 10)
                obj.Minute = "0" + obj.Minute;
            if (obj.Second < 10)
                obj.Second = "0" + obj.Second;

            box.text(obj.Hour + ":" + obj.Minute + ":" + obj.Second);
        }

    </script>
</body>
</html>

Upvotes: 0

Views: 43

Answers (1)

Matthias
Matthias

Reputation: 12259

You are updating the time after the fade in has completed, but before the fade out is done: http://jsfiddle.net/h8kmqsv6/

Try moving the call to UpdateTime to the beginning of fade-in (see http://jsfiddle.net/h8kmqsv6/1/ ):

function fadein() {
   UpdateTime();
   $("#box").fadeIn("500", fadeout);
}
function fadeout() {
   $("#box").fadeOut("500", fadein);
}

UPDATE: For improving synchronization, you can use setInterval:

var $box = $("#box");
$box.fadeOut(0);
setInterval(tick, 1000);

function tick() {
    UpdateTime();

    $box.fadeIn(500, function() {
        $box.fadeOut(500);
    });
}

Link: http://jsfiddle.net/h8kmqsv6/6/

UPDATE2: Stopping the animation inside of tick is also a good idea:

function tick() {
    $box.stop(true, true);

    UpdateTime();

    $box.fadeIn(500, function() {
        $box.fadeOut(500);
    });
}

Link: http://jsfiddle.net/h8kmqsv6/15/

Upvotes: 1

Related Questions