js中setInterval與setTimeout的區別
阿新 • • 發佈:2018-11-11
一、setInterval與setTimeout的區別
1、setInterval
setInterval() 方法可按照指定的週期來呼叫函式(以毫秒為單位)
語法: setInterval(函式表示式,毫秒數);
setInterval() 會不停的呼叫函式,直到clearInterval()被呼叫或者視窗被關閉,
由 setInterval()返回的ID值可用作clearInterval()方法的引數。
2、setTimeout
setTimeout()方法用於在指定毫秒數後再呼叫函式(以毫秒為單位)
語法: setTimeout(函式表示式,毫秒數);
setTimeout()只執行函式一次,如果需要多次呼叫可以使用setInterval()
兩者區別:
setTimeout()方法只執行一次,也就是說當達到設定的時間後就出發運行指定的程式碼,執行完後就結束了。
setInterval()是迴圈執行的,即每達到指定的時間間隔就執行相應的函式或者表示式,是真正的定時器。
二、setTimeout()
兩秒鐘後會彈出框
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>setInterval與setTimeout的區別</title> <script type="text/javascript"> setTimeout("test()", 2000); function test(){alert('setTimeout("test()", 2000);')} </script> </head> <body> </body> </html>
三、clearTimeout()
兩秒鐘後不會彈出框,因為被clearTimeout叫停了
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>setInterval與setTimeout的區別</title> <script type="text/javascript"> var timeId = setTimeout("test()", 2000); function test(){alert('setTimeout("test()", 2000);')} clearTimeout(timeId); </script> </head> <body> </body> </html>
四、setInterval 和 clearInterval
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>setInterval與setTimeout的區別</title>
<script type="text/javascript">
var timeId = setInterval("test()", 2000);
function test(){
var id = confirm('執行clearInterval方法?');
if(id == true){
clearInterval(timeId);
}
}
</script>
</head>
<body>
</body>
</html>