Jump to content

setInterval() crashes Firefox


nick1

Recommended Posts

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);
}

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.