Reputation: 38432
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();
})
Upvotes: 4
Views: 7724
Reputation: 191
Have look in below demo code, which will be updated each second...
<!DOCTYPE html>
<html>
<head>
<title>j</title>
<script type="text/javascript">
function myFunction()
{
setInterval(function(){
var d = new Date();
document.getElementById("dates").innerHTML = new Date(d.getTime());}, 1000);
}
</script>
</head>
<body>
<input type="button" name="e" onclick="myFunction()">
<p id= "dates">ok</p>
</body>
</html>
Upvotes: 0
Reputation: 344803
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.
Change
t = setInterval('tick()',60000);
to
t = setTimeout(tick,60000);
When I first started out coding JavaScript I took down a Lycos web server with AJAX calls because I made the same mistake :-)
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
.
Upvotes: 8
Reputation: 723
As others have pointed out, you are creating new interval every time. Move it to outside your function.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
}
$(document).ready(function(){
t = setInterval(tick,60000);
})
Edit: I'm slow and other answers seem to be updated. So this one is useless now :)
Upvotes: 2
Reputation: 9740
setInterval()
sets an interval. You only need to set it up once, it will get called every 60000ms automatically. setTimeout()
is the one you have to setup every time again.
Upvotes: 3