关于JAVASCRIPT中setInterval函数的一些用法

时间:2023-02-13 09:04:41

就setInterval()方法写了个小DEMO,一个时钟显示,结合了Date类型的API。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript">

function testSetInterval(){
  
    setInterval(clock,1000);
}
function clock(){
  var time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  var year = time.getYear();
  var month = time.getMonth();
  var day = time.getDay();
  var yearDiv = document.getElementById('year');
  yearDiv.innerHTML = year;
  var monthDiv = document.getElementById('month');
  monthDiv.innerHTML = month;
  var dayDiv = document.getElementById('day');
  dayDiv.innerHTML = day;
  var hourDiv = document.getElementById('hour');
  hourDiv.innerHTML = hour;
  var minuteDiv = document.getElementById('minute');
  minuteDiv.innerHTML = minute;
  var secondDiv = document.getElementById('second');
  secondDiv.innerHTML = second;
}

</script>
</head>

<body onload="testSetInterval()">
   <span id="year"></span>年<span id="month"></span>月<span id="day"></span>日&nbsp;&nbsp;&nbsp;&nbsp;<span id="hour"></span>:<span id="minute"></span>:<span id="second"></span>
</body>
</html>

 

 

 

很麻烦,要把年月日时分秒全球一遍。汗呀,忽然发现Date类有一个tolocaleString()方法,马上应用,简单利落呀!

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript">
function testSetInterval(){ 
    setInterval(clock,1000);
}
function clock(){
   var date = document.getElementById('date');       
   date.innerHTML = new Date().toLocaleString();
}

</script>
</head>

<body onload="testSetInterval()">
<div id="date"></div>
</body>
</html>

 

利用setInterval(clock,1000);每隔1秒钟调用clock方法更新页面组件值。达到时钟的效果。

 

实际上setInterval方法还有许多用法,举例说明

有以下两种重载形式

setIntervar(methodname,interval)

setIntervar("methodname(arg1,arg2)",interval)

setIntervar("objname.methodname(arg1,arg2)",interval);

看下面例子:

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript">
function setObjInterval(){
   this.warn = function(warninginfo,times){
   alert('warninginfo is ' + warninginfo + 'and times is '+times);
   }
}
var objInterval = new setObjInterval();

//测试调用对象的方法
function testSetObjInterval(){  
    setInterval("objInterval.warn('time is over', 33)", 2000);
}
function testSetInterval(){ 
    setInterval(clock,1000);
}
function clock(){
   var date = document.getElementById('date');       
   date.innerHTML = new Date().toLocaleString();
}
function setIntervalManyArg(){
   setInterval("showInfo('shl',22)", 2000);
}
function showInfo(name){
   alert('name is ' + name + ' and age is ' + age);
}
</script>
</head>

<body onload="testSetInterval()">
<div id="date"></div>
   <input type='button' value="click me" onclick='testSetObjInterval()'/>
</body>
</html>