一个秒级别计数器:点击“开始"按钮从0开始每隔1秒计数,点击"停止"按钮停止计数。计数停止后,再次点击"开始"按钮继续计数。

效果:
js预览

代码:

<button onclick="myCounter.startCount()">开始</button>
<input id="counter" type="text" readonly="readonly">
<button onclick="myCounter.stopCount()">停止</button>
<button onclick="myCounter.resetCount()">重置</button>

<script>
    var myCounter = (function () {
        var step = 0;
        var intervalId = null;
        function count() {
            document.getElementById("counter").value = step;
            step = step + 1;
        }
        function start() {
            if (intervalId == null) {
                count();
                intervalId = setInterval(count, 1000);
            }
        }
        function stop() {
            clearInterval(intervalId);
            intervalId = null;
        }
        function reset() {
            stop();
            step = 0;
            document.getElementById("counter").value = "";
        }
        return { startCount: start, stopCount: stop, resetCount: reset }
    })()
</script>
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐