我有一个完整的ajax应用程序。我使用以下代码每分钟更新时间。但如果我让浏览器保持打开状态超过10分钟,浏览器就会变得无响应/慢。建议更好的代码。
I have a full ajax application. i am using the below code to update time every minute. But if i keep the browser open for >10 min the browser becomes non responsive/slow. Suggest a better code.
function tick() { var d = new Date(); var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2); $('#WeatherBoLfTime').html(' '+time); t = setInterval('tick()',60000); } $(document).ready(function(){ tick(); })推荐答案
问题是你正在调用 setInterval 很多时间,永远不清除任何一个。所以过了一段时间,你会有大量的间隔回调在大约同一时间运行。
The problem is that you're calling setInterval many times and never clearing any of them. So after a while you have lots of interval callbacks running at around the same time.
更改
t = setInterval('tick()',60000);到
t = setTimeout(tick,60000);当我第一次开始编写JavaScript代码时,我拿了一个带有AJAX调用的Lycos Web服务器,因为我做了同样的错误: - )
When I first started out coding JavaScript I took down a Lycos web server with AJAX calls because I made the same mistake :-)
请注意,由于您显示的是实际时间,因此您应该使用比1分钟短得多的计时器。如果我在13:42:30登陆您的网页,则时间将不会更新,直到~13:43:30。为了使其与机器的时间保持同步,您可能希望将计时器设置为 1000 。
Note that since you're displaying the actual time, you should use a much shorter timer than 1 minute. If I land on your webpage at 13:42:30, the time will not be updated until ~13:43:30. To keep it in sync with the machine's time, you would probably want to set the timer for 1000.
更多推荐
建议一种每分钟更新时间的方法
发布评论