今天 在论坛上看到了关于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=" "+year+"年";
timevalue+=montharray[month]+"月";
timevalue+=((day<10)?("0"+day):day)+"日 ";
timevalue+=(hours<13)?("上午 "+hours):("下午 "+(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 在执行时,它从载入后,每隔指定的时间就执行一次表达式
分享到:
相关推荐
关于JS定时器(setTimeout setInterval)定时不准问题1
前端开发中,我们会会经常使用定时器setinterval setTimeout等,但当我们离开页面时,定时器会被阻塞,导致我们再回到页面的时候定时任务会混乱运行,为些我的解决方案写了个简单demo,希望对你有所帮助
当遇到setInterval,setTimeout与jquery混用的问题 时,直接按JavaScript中的语法写并不起作用,有以下两种解决方法
real-interval 如果你用setTimeout或setInterval实现过网页倒计时功能,你就会发现: 当电脑或者APP休眠了一段时间后,倒计时会出现问题:它比正确的时间慢了。 real-interval能解决这个问题。
博文链接:https://fangyong2006.iteye.com/blog/157398
使用setInterval()模拟进度条 使用setInterval()模拟进度条
Javascript定时器(二)——setTimeout与setInterval 在 http://www.cnblogs.com/strick/p/3983904.html 有说明
window.clearInterval与window.setInterval的用法.
博文链接:https://weiweichen1985.iteye.com/blog/193628
使用SetInterval和设定延时函数setTimeout 很类似。setTimeout 运用在延迟一段时间,再进行某项操作。
NULL 博文链接:https://rainbow702.iteye.com/blog/1668935
html5利用setInterval实现新年元旦倒计时
setInterval setTimeout.html
setinterval倒计 HTML倒计时
但性能测试后发现存在定时器未跟随页面回收的问题,这个可能并不影响使用,但优秀的代码,怎能视而不见,同时这个又关系到小程序的评测指标。 仔细阅读文档后,发现定时器是可回收的,需要以下代码 setTimeout
主要介绍了vue 解决setTimeOut和setInterval函数无效报错的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
06-setInterval.html
在js中如果打算使用setInterval进行倒数,计时等功能,往往是不准确的,针对这个问题,本文有个不错的解决方案