jquery 使用计时器显示当前时间和停止当前时间
<!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>
<script src="./js/jquery-3.6.0.js"></script>
<script>
$(function(){
var timer;
// 为btnStart按钮绑定事件 开始显示
$("#btnStart").click(function(){
//启动计时器
timer=setInterval(()=>{
// 获取当前时间
var now=new Date();
var year=now.getFullYear();
var month=now.getMonth()+1;
var day=now.getDate();
var hour=now.getHours();
var minute=now.getMinutes();
var second=now.getSeconds();
var currentTime=year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒";
$("#currentTime").text(currentTime);
},1000)
})
// 为btnStop按钮绑定事件 停止显示
$("#btnStop").click(function(){
// 停止计时器
clearTimeout(timer)
})
})
</script>
</head>
<body>
<button id="btnStart">开始显示当前时间</button>
<button id="btnStop">停止显示当前时间</button>
<h2 id="currentTime"></h2>
</body>
</html>




浙公网安备 33010602011771号