Reputation: 647
Good morning, I created a function that gets all the USA timezone times and returns them to me highlighting which timezone you are in. The issue is I want it to run every minute. When I use the setInterval function I keep getting a javascript error saying 'invalid argument'. Here is my code in jsFiddle http://jsfiddle.net/Qg2eL/
// Timezone
var arrTime = new Array();
var arrZone = new Array("ET","CT","MT","PT");
var getTimeZones = setInterval(timeZone(),60000);
function timeZone(){
var location = 0;
var current_date = new Date();
var offset = parseInt(-current_date.getTimezoneOffset() / 60);
switch(offset){
case -5:
location = 0;
break;
case -6:
location = 1;
break;
case -7:
location = 2;
break;
case -8:
location = 3;
break;
}
arrTime.length = 0;
for(var x=5; x<9; x++){
var current_date = new Date();
var utc_hour = current_date.getUTCHours() - x;
var utc_minutes = current_date.getUTCMinutes().toString();
var dd = "AM";
if(utc_hour >= 12){
utc_hour = utc_hour - 12;
dd = "PM";
}
if(utc_hour == 0){ utc_hour = 12; }
utc_minutes = utc_minutes<10?"0"+utc_minutes:utc_minutes;
var formattedTime = utc_hour+":"+utc_minutes+" "+dd;
arrTime.push(formattedTime);
}
var strHTML = "";
strHTML += "<ul>";
for(var x=0; x<arrTime.length; x++){
strHTML += "<li>"+arrZone[x]+": "+arrTime[x]+"</li>";
}
strHTML += "</ul>";
$('.timezoneHolder').html(strHTML);
$('.timezoneHolder ul li:nth-child('+(location+1)+')').css({
"color":"lime",
"font-weight":"bold"
});
}
Upvotes: 0
Views: 782
Reputation: 7117
Very common mistake is that you're not passing the function to be executed but actually calling it in this line:
var getTimeZones = setInterval(timeZone(),60000);
Rather:
var getTimeZones = setInterval(timeZone,60000);
PS. tested in Chrome and IE. and no invalid argument popped up.
Edit: The reason you're not seeing it pop up after making your change is because it will only be executed after 60 seconds, so you should just call the function after your setInterval
and will be executed every 60 seconds afterwards.
var getTimeZones = setInterval(timeZone,60000);
timeZone();
Upvotes: 2
Reputation: 12508
The setInterval function runs its own "callback" you could say. The syntax is just a little off. Try this:
var getTimeZones = setInterval(function() {
timeZone();
},60000);
This syntax basically says, every 60000 milliseconds (or 60 seconds) perform the function inside of the interval. In this case the setInterval function calls your function.
Hope this helps.
Upvotes: 2
Reputation: 495
var getTimeZones = setInterval(timeZone,60000);
remove the brackets! :)
Upvotes: 1