一.setInterval()与setTimeout()的定义:
二.setInterval()与setTimeout()的使用:
1.setInterval()与clearInterval()
<button id="btn" onclick="stopTime()">按钮</button> <p id="ptime"></p> <script type="text/javascript"> var mytime = setInterval(function(){ getTime(); //函数调用 },1000); //1000毫秒 function getTime(){ var d = new Date(); var t = d.toLocaleTimeString(); //将日期对象时分秒转换成字符串 document.getElementById('ptime').innerHTML = t; } function stopTime(){ clearInterval(mytime); }
1.setTimeout()与clearTimeout()
<body onload="getHello()"> <button id="btn" onclick="stopHello()">按钮</button> <p id="ptime"></p> <script type="text/javascript"> var myinfo; function getHello(){ alert("hello"); myinfo = setTimeout(function(){getHello()},3000); } function stopHello(){ clearTimeout(myinfo); }
3.区别
setTimeout()是对自身的调用执行,setInterval()是延迟执行