window.setInterval:
让id="clock"展示当前时间,并随时间变化
按钮的作用为时间停止
这种写法存在问题:页面加载完毕时间会晚一秒出现。解决方案:先执行一次clock()方法,或者把执行间隔时间改为100
<html>
<body>
<input type="text" id="clock" size="35" />
<script language=javascript>
// clock();
var i=self.setInterval("clock()",1000)
function clock() {
var t=new Date()
document.getElementById("clock").value=t
}
</script>
<button onclick="i=window.clearInterval(i)">Stop interval</button>
</body>
</html>
setTimeout:
<html>
<body>
<input type="text" id="clock" size="35" />
<script language=javascript>
// clock();
var i=setTimeout(clock,1000);
function clock() {
clearTimeout(i);
var t=new Date()
document.getElementById("clock").value=t
i = setTimeout(showTime,1000);
}
</script>
<button onclick="i=window.clearTimeout(i)">Stop</button>
</body>
</html>