- setInterval
var delay = 1000
var timer = setInterval(function(){
console.log(a)//会每隔1秒打印一次a
},delay)//当delay改变时没有用,定时器只有第一次timer有效
clearInterval(1)//清除定时器的方法
- setTimeout
var delay = 1000
var timer = setTimeout(function(){
console.log(a)//只打印一次a
},delay)
clearTimeout(timer)//`清除定时器`
3.他们全是window上的方法,内部函数this指向window
4.实现一个三分钟的计时器
<body>
minutes:<input type='text' value='0'/>
seconds:<input type='text' value='0'/>
</body>
<script>
var minutesNode = document.getElementByTagName('input')[0]
var secondsNode = document.getElementByTagName('input')[1]
var minutes = 0,
seconds = 0
var timer = setInterval(function(){
seconds ++;
if(seconds == 60){
seconds = 0;
minutes ++;
}
secondsNode.value = seconds;
minutesNode.value = minutes;
if(minutes == 3){
clearInterval(timer)
},10)
</script>