<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2></h2> <button>clearTimeout</button> <button>clearInterval</button> <script type="text/javascript"> var h2 = document.getElementsByTagName(‘h2‘)[0]; //获取时间,每隔1s,更新 var t1 = setInterval(function(){ var d1 = new Date(); var y = d1.getFullYear(); var m = d1.getMonth() + 1; var d = d1.getDate(); var h = d1.getHours(); var i = d1.getMinutes(); var s = d1.getSeconds(); //构造表示时间的字符串 var str = y + "年" + m +"月" + d + "日" + h + "时" + i + "分" + s + "秒"; h2.innerHTML = str; //写入到h2标签中 },1000); </script> <script type="text/javascript"> function f1(){ console.log(‘setTimeout‘); } var t1 = window.setTimeout(f1,1000); console.log( t1 ); var btns = document.getElementsByTagName(‘button‘); btns[0].onclick = function(){ clearTimeout(t1); } var t2 = setInterval(function(){ console.log( ‘setInterval‘ ); },1500); btns[1].onclick = function(){ clearInterval(t2); } </script> </body> </html>