2018年2月23日 星期五

瀏覽器的分時著色

// 當你頻繁要瀏覽器著色

// 瀏覽器會自己排對列,不要我們幫他搞


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div.box {
            height: 100px;
            width: 100px;
            background-color: #0F0;
            opacity: 0.01;
            position: absolute;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
        }
    </style>
    <script src="../js_lib/jquery-3.3.1.min.js"></script>
    <script>
        let count = 0;

        function t_1() {
            // count = 0;
            $('#msg_1').html(++count);

            (function (count) {
                domList.forEach(function ($dom) {
                    $dom.html(count);
                });
            })(count);
        }


        function t_2() {
            // count = 0;
            $('#msg_1').html(++count);

            (function (count) {
                setTimeout(function () {
                    domList.forEach(function ($dom) {
                        $dom.html(count);
                    });
                }, 0);
            })(count);
        }


        function t_3() {
            // count = 0;
            $('#msg_1').html(++count);

            (function (count) {
                domList.forEach(function ($dom) {
                    // 分時 render 不可行
                    // 應交由瀏覽器自己去安排
                    setTimeout(function () {
                        $dom.html(count);
                    }, 0);
                });
            })(count);
        }

    </script>
</head>

<body>
    <div>
        <p>
            <button onclick="t_1()">go_1</button>
        </p>
        <p>
            <button onclick="t_2()">go_2</button>
        </p>
        <p>
            <button onclick="t_3()">go_3</button>
        </p>
    </div>
    <div id="msg_1">

    </div>
    <div id="msg_2">

    </div>
    <hr>
    <div id="container">

    </div>

    <script>
        let domList = [];
        (function () {

            let startTime = (new Date()).getTime();
            for (let i = 0; i < 5000; i++) {
                let $dom = $('<div>0</div>').addClass('box')

                domList.push($dom);

                $dom.appendTo('#container');
            }
            let endTime = (new Date()).getTime() - startTime;
            $('#msg_2').html(endTime);
        })();

    </script>
</body>

</html>