nick1 Posted July 24, 2008 Share Posted July 24, 2008 Greetings, The following JavaScript code displays a clock in a <p id="time"></p> element on a web page and updates the clock once per minute. When letting this code run for ~10 minutes under FireFox 2.0.0.16 on Ubuntu 6.10 and Mac OS X, Firefox eventually becomes unresponsive. A CPU check shows Firefox consuming +100% of the CPU. Am I losing my mind or did I code something incorrect? I'd appreciate your thoughts. Thanks. window.onload = function() { /* * Execute the following functions in the order they appear after the webpage loads. * The reason being, the DOM needs to finish loading in order for these functions to * manipulate certain elements. */ displayTime(); } function displayTime() { var date = new Date(); var hour = date.getHours(); // Returns 0-23. var minutes = date.getMinutes(); // Returns 0-59. // Is it AM or PM? if (hour >= 12) { var ampm = "PM"; } else { ampm = "AM"; } // Convert hours format from 24 hour to 12 hour format. if (hour > 12) { hour = hour - 12; } // Convert hour 0 to 12. if (hour == 0) { hour = 12; } // Convert minutes format to mm for 0-9. if (minutes < 10) { minutes = "0" + minutes; } // Put everything together to form the current time. var time = hour + ":" + minutes + " " + ampm; // Display the time on the webpage. var paraTime = document.getElementById("time"); if (paraTime.childNodes.length > 0) { // Meaning it has childNodes. hasChildNodes doesn't work. paraTime.removeChild(paraTime.firstChild); } paraTime.appendChild(document.createTextNode(time)); // Update the clock every one minute. setInterval(displayTime, 60000); } Quote Link to comment Share on other sites More sharing options...
nick1 Posted July 25, 2008 Author Share Posted July 25, 2008 EDIT: Nevermind, I figured out what the problem was. I'm embarrassed, haha. I decided to replace setInterval with setTimeout, since setTimeout executes displayTime once and then stops. Whereas setInterval continuously executes a piece of code. So, after 10 minutes, 11 intervals would be scheduled - not what I wanted. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.