javascript中setInterval,setTimeout的区别跟用法

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
setTimeout只运行一次,也就是说设定的时间到后就触发运行指定代码,运行完后即结束。

下面是setInterval来取货系统当前时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>获取系统时间</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
*{
    margin: 0px; padding: 0px; font-size:14px; font-family:‘微软雅黑‘;
}
.clearfix:after{content:‘.‘;display:block;height:0;clear:both;visibility:hidden}
.clearfix{display:inline-block;}
* html .clearfix{height:1%}
.clearfix{display:black;}
ul li{
  list-style:none;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
showTime();
function toDou(num){
  if(num<10){
    return ‘0‘+num;
  }else{
    return ‘‘+num;
  }
function showTime(){
  var date = new Date();
  var Time = $(‘Nowtime‘);
  var str = toDou(date.getFullYear())+‘年‘+toDou(date.getMonth())+‘月‘+toDou(date.getDate())+‘日‘+toDou(date.getHours())+‘时‘+toDou(date.getMinutes())+‘分‘+toDou(date.getSeconds())+‘秒‘;
  Time.innerHTML = str;
}
setInterval(showTime,1000);
}
function $(id){
  return document.getElementById(id);
}
</script> 
<p>现在时间:<span id=‘Nowtime‘></span></p>
</body>
</html>

下面是用setInterval与clearInterval简单的用法

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>setInterval与clearInterval</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
*{
margin: 0px; padding: 0px; font-size:14px; font-family:‘微软雅黑‘;
}
.clearfix:after{content:‘.‘;display:block;height:0;clear:both;visibility:hidden}
.clearfix{display:inline-block;}
* html .clearfix{height:1%}
.clearfix{display:black;}
ul li{
list-style:none;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var oBtn = $(‘btn‘);
var oBtn1 = $(‘btn1‘);
var oTxt = $(‘txt‘);
var i=0;
var timer = null;
oBtn.onclick = function(){
timer = setInterval(function(){
i++;
oTxt.value = i;
if(i==100){
clearInterval(timer);
}
},1000);
}
oBtn1.onclick = function(){
clearInterval(timer);
}
}
function $(id){
return document.getElementById(id);
}
</script>
<input type=‘text‘ id=‘txt‘ value=‘0‘><input type=‘button‘ value=‘开始‘ id=‘btn‘><input type=‘button‘ value=‘关闭‘ id=‘btn1‘>
</body>
</html>

javascript中setInterval,setTimeout的区别跟用法,布布扣,bubuko.com

javascript中setInterval,setTimeout的区别跟用法

上一篇:Java Web总结七


下一篇:堆放木块C++实现