天天看點

Window setInterval() 方法

Window setInterval() 方法

Window 對象

每三秒(3000 毫秒)彈出 "Hello" :

setInterval(function(){ alert("Hello"); }, 3000);

使用一個代碼字元串:

setInterval('alert("Hello");', 3000);

setInterval() 方法可按照指定的周期(以毫秒計)來調用函數或計算表達式。

setInterval() 方法會不停地調用函數,直到 clearInterval() 被調用或視窗被關閉。由 setInterval() 傳回的 ID 值可用作 clearInterval() 方法的參數。

<b>提示:</b> 1000 毫秒= 1 秒。

提示: 如果你隻想執行一次可以使用 setTimeout() 方法。

表格中的數字表示支援該屬性的第一個浏覽器版本号。

方法

setInterval()

1.0

4.0

參數

描述

code/function

必需。要調用一個代碼串,也可以是一個函數。

milliseconds

必須。周期性執行或調用 code/function 之間的時間間隔,以毫秒計。

param1, param2, ...

可選。 傳給執行函數的其他參數(IE9 及其更早版本不支援該參數)。

傳回值:

傳回一個 ID(數字),可以将這個ID傳遞給clearInterval(),clearTimeout() 以取消執行。

你可以通過調用一個已命名的函數,每三秒(3000 毫秒)彈出 "Hello":

var myVar;

function myFunction() {

myVar = setInterval(alertFunc, 3000);

}

function alertFunc() {

alert("Hello!");

顯示目前時間( setInterval() 方法會每秒執行一次函數,類似手表功能):

var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {

var d = new Date();

var t = d.toLocaleTimeString();

document.getElementById("demo").innerHTML = t;

使用 clearInterval() 來停止 setInterval 的執行:

function myStopFunction() {

clearInterval(myVar);

使用 setInterval() 和 clearInterval()來建立動态進度條:

function move() {

var elem = document.getElementById("myBar");

var width = 0;

var id = setInterval(frame, 10);

function frame() {

if (width == 100) {

clearInterval(id);

} else {

width++;

elem.style.width = width + '%';

每 300 毫秒切換背景顔色:

var myVar = setInterval(function(){ setColor() }, 300);

function setColor() {

var x = document.body;

x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";

function stopColor() {

傳遞參數給 alertFunc 函數 ( IE9 及其更早版本不支援):

function myStartFunction() {

myVar = setInterval(alertFunc, 2000, "Runoob", "Google");

但是,如果使用匿名函數,則所有浏覽器都支援:

myVar = setInterval(function(){ alertFunc("Runoob", "Google"); }, 2000);

Window 對象: clearInterval() 方法

Window 對象: setTimeout() 方法

Window 對象: clearTimeout() 方法

Window setInterval() 方法