使用面向对象并模块化编程写一个JavaScript简单计时器

时间:2021-10-09 07:51:29

模块化编程我使用了requireJS,最近新看的,菜鸟驿站学的,很简单很入门的教程.传送带 W3C的require教程

下边直接上代码:

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

    <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>
        <script type="text/javascript" src="js/require.js"></script>
        <!--谷歌浏览器无法加载配置文件-->
        <script type="text/javascript" src="js/jquery.js" ></script>
        <script>
            require.config({
                paths: {
                    "jquery": ["https://cdn.bootcss.com/jquery/1.10.2/jquery.min", "js/jquery"],
                    "b": "js/b" 
                }
            })
            require(["jquery", "b"]);
        </script>
    </head>
    <body>
        <div>
            <span class="s1"></span>
            <button id="btn1">开始计时 </button>
            <button id="btn2">停止计时</button>
        </div>
    </body>

</html>

b.js

define(function() {
    function fu1() {
        $(function() {
            var timer;
            var timekeeping = {
                start: function() {
                    var b = 0;
                    if(timer == null) {
                        timer = window.setInterval(function() {
                            b++;
                            $(".s1").html(b);
                            console.log(b);
                        }, 1000);
                    }
                },
                stop: function() {
                    window.clearInterval(timer);
                    timer = null;
                }

            };
            $("#btn1").on("click", function() {
                timekeeping.start();

            })
            $("#btn2").on("click", function() {
                timekeeping.stop();

            })

        })
    }
    fu1();
})