setInterval()

Function: Repeatedly call a function or execute a code segment with a fixed time delay between each call.

Usage: switch between two colors

<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>setInterval/clearInterval example</title>
<script type="text/javascript">
var nIntervId;

function changeColor() {  //每一秒执行一次flashText()
  nIntervId = setInterval(flashText, 500);
}

function flashText() {  //颜色变化
  var oElem = document.getElementById("my_box");
  oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}

function stopTextColor() { //停止颜色转换
  clearInterval(nIntervId);
}
</script>
</head>

<body onload="changeColor();">
<div id="my_box">
<p>Hello World</p>
</div>
<button onclick="stopTextColor();">Stop</button>
</body>
</html>

Learn more about the setInterval() method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325494380&siteId=291194637