`
wwwzhouhui
  • 浏览: 358697 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

setInterval 引起的性能问题

阅读更多

 今天 在论坛上看到了关于setInterval  和setTimeout 在用一位置表现出不通的性能问题

代码如下:

example.js

var montharray = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12")
document.write("<span id=clock></span>");
function getthedate(){
    var date = new Date();
	
	var year = date.getYear()
    if (year < 1000) 
        year += 1900
	var month=date.getMonth();
	var day=date.getDate();
	var hours=date.getHours();
	var minutes=date.getMinutes();
  var second = date.getSeconds();
	
	var timevalue="&nbsp;"+year+"年";
	
	timevalue+=montharray[month]+"月";
	timevalue+=((day<10)?("0"+day):day)+"日&nbsp;&nbsp;";
	
	timevalue+=(hours<13)?("上午&nbsp;"+hours):("下午&nbsp;"+(hours-12))+"时";
	
	timevalue+=((minutes<10)?("0"+minutes):minutes)+"分";
	timevalue+=((second<10)?("0"+second):second)+"秒";


    document.getElementById("clock").innerHTML = timevalue;
    
    window.setInterval("getthedate()", 1000);
}
getthedate();

   time.htm

 

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
        <title>Untitled Document</title>
    </head>
    <body>
		    </body>
</html>

 运行结果表现 CPU 占用很高 一会IE 会吊死。

网上有2中方法修改

1:将 window.setInterval("getthedate()", 1000); 换成window.setTimeout("getthedate()", 1000);

2:将getthedate 方法里面的window.setInterval("getthedate()", 1000) 去掉,JS 代码中最后的getthedate换成 window.setInterval("getthedate()", 1000)

运行后表现良好

分析:

setTimeout (表达式,延时时间)
setInterval(表达式,交互时间)
延时时间/交互时间是以豪秒为单位的(1000ms=1s)

setTimeout   在执行时,是在载入后延迟指定时间后,去执行一次表达式,仅执行一次
setInterval 在执行时,它从载入后,每隔指定的时间就执行一次表达式

 

分享到:
评论
3 楼 Dead_knight 2012-09-17  
ft284800 写道
无意中搜到了这个,但这不是两者的性能问题,是你的程序设计问题,用setInterval怎么可以放程序里呢?

setInterval放到方法里没问题,关键是setInterval所执行的方法就是该语句所在的方法。这样产生的问题很明显,是个死循环了。
其实setInterval方法的作用主要就是做js层的定时任务。
2 楼 shanhuhai 2012-03-14  
没错,是程序的问题,把setInterval 放在函数中,结果每次都会 增加一个 setInterval 时钟,然后 setInterval的个数会以 2次方的形式增长,最后导致 浏览器卡死
1 楼 ft284800 2011-09-30  
无意中搜到了这个,但这不是两者的性能问题,是你的程序设计问题,用setInterval怎么可以放程序里呢?

相关推荐

Global site tag (gtag.js) - Google Analytics