js如何用if语句启动计时器

JavaScript013

js如何用if语句启动计时器,第1张

s js如何用if语句启动计时器 方法如下,etTimeout

定时执行,在设定时间后会执行代码的内容,如

setTimeout(function(){

console.log('aa')

},1000)

在1秒后(1000毫秒)控制台打印aa

setInterval

每隔设定的时间执行一次代码,如

setInterval(function(){

console.log('aa')

},1000)

每1秒(1000毫秒)在控制台打印aa,直到使用clearInterval停止

点击开始计时时先调用停止计时函数和重置函数再调用开始计时函数就可以了。

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>计时器</title>

    <script type="text/javascript">

        var c = 0

        var t

        var onOff = true

        function timedCount() {

            document.getElementById('txt').value = c

            c = c + 1

            t = setTimeout("timedCount()", 1000)

        }

        function stopCount() {

            clearTimeout(t)

        }

        function cs() {

            c = 0

            document.getElementById('txt').value = 0

        }

    </script>

</head>

<body>

    <form>

        <input id="btn1" type="button" value="开始计时" onclick="stopCount()cs()timedCount()">

        <input type="text" id="txt">

        <input type="button" value="停止计时" onclick="stopCount()">

        <input type="button" value="重置" onclick="cs()">

    </form>

    <p>当点击“开始计时”的按钮时,从0开始一直进行计时,当点击“停止计时”按钮时停止计时。</p>

</body>

</html>