Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Abe Layee
8,378 PointsCalling Anonymous Function with setTimeout() method
Hello all. How are you doing today? I hope you're better:D Anyway, I am having some problem calling my anonymous function with setTimeout(). I tried preventing the function from running by deleting the at the end of the curly braces but is not working. Here is my code. I don't what I am doing wrong.
var diem = "Am";
(function() { //anonymous function with no name
var newDate = new Date(); // new date object
var h = newDate.getHours(); // get the hour from the date object
var m = newDate.getMinutes(); // get the minutes from the date object
var s = newDate.getSeconds(); // get the seconds from the hour object
var elDate = document.getElementById('date'); // get the date element
var elTime = document.getElementById('time'); // get the time element
// if hour is equal to 0, add 12 to it.
if (h===0) {
h = 12;
}
/* change the hour format from 24 to 12 and
Diem to Pm if the hour is greater than 12 */
if (h>12) {
h = h-12;
diem = "PM";
console.log(h +":" + diem);
}
else if (h < 10) {
h = 0 + hour;
}
else if(m <10) {
m = 0 + m; // add zero to the minutes
}
else if (s < 10) {
s = 0 + s; // add zero to the second.
}
// Call the anonymous function every one second with the setTimeout() method
var runAnonymousFunction = setTimeout(function(),1000); // this my error right here.
})();
2 Answers

rydavim
18,814 PointsYou can't 'call' an anonymous function later on in your code. If you want to do that, you will need to store the function in a variable so that you can reference it later.
If you want to use an anonymous function, you need to include the code inside the function.
var runAnonymousFunction = setTimeout(function(){
// The code you want to run goes here.
},1000);
Additionally, it doesn't sound like setTimeout is the method you want to be using. From the w3schools page: The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
Maybe setInterval would work better for you? The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.
Please let me know if you have any other questions!

Abe Layee
8,378 Pointsaww, thank you. I learn something new everyday.