codenoob codenoob - 1 year ago 124
Javascript Question

Javascript clock / timer breaks

I am planning to build multiple timer. I started by building a simple clock using the following code.

the issue is, the clock will run for a few minute and the website will break, I think it's due to running out of memory.

when I console.log the output. It appears the command is ran more than once per second. The counter for the console.log line will say 2, 4, 8, 16, 32, 64 etc etc. quickly doubling into some astronomical number. and the site will become non responsive in a few minute.

Is it an efficiency issue with the code?
Or it is just not feasible to use java script to up date something every second.
because I am planning on making multiple timer on the same page. (maybe around 5-10)

I tried this on google chrome.

function updateTime() {
var d = new Date;
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
var ampm = 'AM';
if (hours >= 12) {
ampm = 'PM';
if (hours > 12) {
hours = hours - 12;
formatted_time = hours + ':' + mins + ':' + secs + ampm;
window.setInterval(updateTime, 1000);

Answer Source

You're probably running out of memory because each new setInterval call starts a periodic function.

So each time updateTime is called, a new one is started. That means 1 call, 2 calls, 4 ... 2^n. (after 60 seconds you will have 2^60 calls. This is a 18 digit decimal number).Calls in just n seconds. You probably meant to use setTimeout

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download