再帰関数を使用して setTimeout を実装し、setInterval 効果をシミュレートします

必要:

ページは現在時刻を 1 秒ごとに出力します

現在時刻を出力するには、 new Date().toLocaleString() を使用できます。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div></div>
    <script>
        function getTime(){
            document.querySelector('div').innerHTML=new Date().toLocaleString()
            setTimeout(getTime,1000)
        }
        getTime()
    </script>
</body>
</html>

コードは非常にシンプルで、主に再帰の考え方を強調しています。

おすすめ

転載: blog.csdn.net/L19541216/article/details/130084133