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"
});
}
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();
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.
var getTimeZones = setInterval(timeZone,60000);
remove the brackets! :)
Related
I have to do a timer in javascript with timing events, the time units should be in milliseconds.
i need something like this:
start_timer
//some code..
stop_timer
//and then show the ms
sorry for my english, and thank you for help!
edit:
i tried this method as test:
var d = new Date();
var time = d.toLocaleTimeString();
var myVar = window.setInterval(function(time){ time -= d.toLocaleTimeString()
return code.value = time.toString();
}, 5000);
The console.time method is perfect but if you want to keep the result in memory you have to use the Date.now method.
let now = Date.now();
for (let i = 0; i < 100000; ++i)
// ...
// Result in milliseconds.
let result = Date.now() - now;
// If you want to show it in a input box.
input.value = result + "ms";
You can use console.time(), for the browsers that support it:
console.time('Stuff')
for (var i = 0; i < 1000; i++) {
// run some code
}
console.timeEnd('Stuff')
Hi I want to use 3 different counters that show me 3 different increasing numbers starting from a certain date. I've tryed this:
<script>
var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_1 = 5; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var count_1 = 0;
window.onload = function()
{
var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = new Date();
count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
document.getElementById('counter_1').innerHTML = count_1;
setInterval("count_1 += INCREMENT_1; document.getElementById('counter_1').innerHTML = count_1;", msInterval_1);
}
</script>
<script>
var START_DATE_2 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_2 = 5; // in seconds
var INCREMENT_2 = 1; // increase per tick
var START_VALUE_2 = 0; // initial value when it's the start date
var count_2 = 0;
window.onload = function()
{
var msInterval_2 = INTERVAL_2 * 1000;
var now_2 = new Date();
count_2 = parseInt((now_2 - START_DATE_2)/msInterval_2) * INCREMENT_2 + START_VALUE_2;
document.getElementById('counter_2').innerHTML = count_2;
setInterval("count_2 += INCREMENT_2; document.getElementById('counter_2').innerHTML = count_2;", msInterval_2);
}
</script>
<script>
var START_DATE_3 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_3 = 5; // in seconds
var INCREMENT_3 = 1; // increase per tick
var START_VALUE_3 = 0; // initial value when it's the start date
var count_3 = 0;
window.onload = function()
{
var msInterval_3 = INTERVAL_3 * 1000;
var now_3 = new Date();
count_2 = parseInt((now_3 - START_DATE_3)/msInterval_3) * INCREMENT_3 + START_VALUE_3;
document.getElementById('counter_3').innerHTML = count_2;
setInterval("count_3 += INCREMENT_3; document.getElementById('counter_3').innerHTML = count_3;", msInterval_3);
}
</script>
<div id="counter_1"></div>
<div id="counter_2"></div>
<div id="counter_3"></div>
This doesn't work as expected and only the 3td div is populated but now working as expected too (as soon as I load the page it show me a number then after few seconds restart from 1).
What's wrong? How should I do it without using JQuery also?
Thanks in advance.
I don't do a code analysis - this would be something for SE-CodeReview (highly recommended to post there too once you got it working), but your error is, that you are assigning something to a function more than once - hence, only the last assignment is actually called onload.
So -- you are assigning window.onload = function() in your first <script> tag, then you are overriding it in your second; and you're overriding the second assignment again in your third <script> tag.
You can't do that if you want to assign all 3 functions to a single (onload) event.
If you want to add multiple listeners for a single event, use
document.addEventListener("DOMContentLoaded", function() {});
Now inside that function, you can add all your code that you want to have executed onload of your page; in addition to the code you wanted to have executed onload in another function!
Here's a simple demonstration using the same techniques as described above, but with click listeners. Notice the first function will never be called.
document.getElementById("a").onclick = function() {
alert("I will never alert, because of the next function");
}
document.getElementById("a").onclick = function() {
alert("I will alert, because I'm not overriden");
}
document.getElementById("a").addEventListener('click', function() {
alert("I will alert too");
});
document.getElementById("a").addEventListener('click', function() {
alert("And a third alert. Disturbing");
});
<div id="a">Click me!</div>
I have a game that I am making using only pure javascript. Instead of a GUI, It is more like the old command line games and uses a prompt for input.
One of the main components of it is the Clock, which is expressed in hours, and can be checked with the commmand "time" and tells them the value of the variable "time". Here is the code:
var timestrt = 1;
var timer = setInterval(function(){timestrt++;return timestrt;}, 86000); var time = timestrt;
After testing it, I realized that the clock was not changing. So I set it to 10 seconds instead of 86 to be sure that I was waiting long enough, and it still did not want to work
I know that it is probably caused by the prompt and constant alerts, but I am not sure even where to start for a workaround.
Any ideas?
Edit: is it possible to either
1. retrieve the timer from an external page
2. comparing it to an actual clock in real time or 3. Using a animated gif clock in the background and calculating the location of certain pixels as time?
Don't use the native prompts and dialogs, since they stop the script execution time. Instead use simulated ones, for example jQuery IU has prompts and dialog boxes that do not stop execution. Here is an example of that:
$(function() {
$( "#dialog" ).dialog();
var timestrt = 1;
var timer = setInterval(function(){
timestrt++;
var time = timestrt;
$("#time").text(time);
}, 1000);
});
Here is my workaround:
This code is called before the prompt is started:
function initTime() {
var now = new Date();
stS = now.getSeconds();
stM = now.getMinutes();
stH = now.getHours();
}
This is called after the prompt is done:
function computeTime() {
var now = new Date();
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
Then I convert it to seconds to make it easier to check against:
var finalH = elapH * 3600;
var finalM = elapM * 60;
var finalS = finalM + elapS + finalH;
And check/change the time variable based on how many sets of 86 seconds has passed:
if (finalS > 86 && finalS < 172) {
time = 1;
}
if (finalS > 172 && finalS < 258) {
time = 2;
}
if (finalS > 258 && finalS < 344) {
time = 3;
}
if (finalS > 344 && finalS < 430) {
time = 4;
}
if (finalS > 430 && finalS < 516) {
time = 5;
}
if (finalS > 516) {
time = 6;
alert('5 A.M.');
alert('A clock is chiming...');
alert('6 A.M.');
playing = false;
alert('Thanks for playing! Goodbye!');
}
And that is my alternative to using a setinterval/timer behind multiple prompts and alerts. The last part probably wasn't needed, but since it answered my original question I included it.
Does any one know if it is possible to continuously run a JavaScript in the console window without it stopping when the page gets reloaded.
Here is the script I want to run, all it will do is change the dates and click a button. However when the button is clicked, my script stops. Is there any way around this?
var sDate = document.getElementById('START_DATE');
var eDate = document.getElementById('END_DATE');
var btn = document.getElementById('ExcelDataOnly');
var d = new Date();
d.setMonth(0);
d.setDate(1);
d.setFullYear(2012);
function pad(num, size){
var s = "00" + num;
return s.substr(s.length-size);
}
for(var i = 1; i < 365; i++){
var dt = [pad(d.getMonth()+1,2),
pad(d.getDate(),2),
d.getFullYear()].join("/");
console.log("Date:", dt);
sDate.value = dt;
eDate.value = dt;
btn.click();
while(document.readyState !== "complete") {console.log("Sleeping");};
d.setDate(d.getDate()+1);
}
As you can see from the code, it should do the for loop but it stops after the first round because the page reloads itself.
I have 2 javascripts who aren't working together. They both work separately, but when put together only one works. This is how I called them
window.onload = initImages;
window.onload = countdown(year,month,day,hour,minute);
If I put "window.onload = initImages;" after "countdown", then only images work, if it stays like this when countdown is after images, then only countdown works.
// JavaScript Document
function initImages() {
for (var x = 0; x < document.images.length; x++)
{
document.images[x].onclick = povecana;
}
}
function povecana() {
dir = "images/" + this.id + ".jpg";
if (undefined != window.proz)
{
proz.style.opacity = 0.6;
}
proz = document.getElementById(this.id);
proz.style.opacity = 1;
slika = document.getElementById("odabranaSlika");
slika.style.display= "block";
slika.innerHTML='<img src='+ dir +' " width="100%" height="450px" />';
jabuke = document.getElementById("default");
jabuke.style.display= "none";
tekst = document.getElementById("tekstOdabrane");
tekst.style.display = "block";
if (this.id=="slika1")
tekst.innerHTML="Idared je američka sorta nastala 1935.";
else (this.id=="slika2")
tekst.innerHTML="Fuji je zasigurno jedna od atraktivnijih";
}
/*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items noted in light blue below to create your countdown target date and announcement once the target date and time are reached. */
var current="Winter is here!";//-->enter what you want the script to display when the target date and time are reached, limit to 20 characters
var year=2013; //-->Enter the count down target date YEAR
var month=12; //-->Enter the count down target date MONTH
var day=21; //-->Enter the count down target date DAY
var hour=18; //-->Enter the count down target date HOUR (24 hour clock)
var minute=38; //-->Enter the count down target date MINUTE
var tz=+1; //-->Offset for your timezone in hours from UTC (see http://wwp.greenwichmeantime.com/index.htm to find the timezone offset for your location)
//--> DO NOT CHANGE THE CODE BELOW! <--
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
function countdown(yr,m,d,hr,min){
theyear=yr;themonth=m;theday=d;thehour=hr;theminute=min;
var today=new Date();
var todayy=today.getYear();
if (todayy < 1000) {todayy+=1900;}
var todaym=today.getMonth();
var todayd=today.getDate();
var todayh=today.getHours();
var todaymin=today.getMinutes();
var todaysec=today.getSeconds();
var todaystring1=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
var todaystring=Date.parse(todaystring1)+(tz*1000*60*60);
var futurestring1=(montharray[m-1]+" "+d+", "+yr+" "+hr+":"+min);
var futurestring=Date.parse(futurestring1)-(today.getTimezoneOffset()*(1000*60));
var dd=futurestring-todaystring;
var dday=Math.floor(dd/(60*60*1000*24)*1);
var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
if(dday<=0&&dhour<=0&&dmin<=0&&dsec<=0){
document.getElementById('count2').innerHTML=current;
document.getElementById('count2').style.display="inline";
document.getElementById('count2').style.width="390px";
document.getElementById('dday').style.display="none";
document.getElementById('dhour').style.display="none";
document.getElementById('dmin').style.display="none";
document.getElementById('dsec').style.display="none";
document.getElementById('days').style.display="none";
document.getElementById('hours').style.display="none";
document.getElementById('minutes').style.display="none";
document.getElementById('seconds').style.display="none";
document.getElementById('spacer1').style.display="none";
document.getElementById('spacer2').style.display="none";
return;
}
else {
document.getElementById('count2').style.display="none";
document.getElementById('dday').innerHTML=dday;
document.getElementById('dhour').innerHTML=dhour;
document.getElementById('dmin').innerHTML=dmin;
document.getElementById('dsec').innerHTML=dsec;
setTimeout("countdown(theyear,themonth,theday,thehour,theminute)",1000);
}
}
window.onload = function() {
initImages();
countdown(year,month,day,hour,minute);
}
They are being overwritten. You can't assign two values to one variable!
For example,
x = 5;
x = 10;
Of course, x will be 10. Well, it is the same for you: window.onload is like x and the numbers are like your functions.
window.onload = func1;
window.onload = func2;
in this case always func 2 will be called as you have changed the onload handler from func1 to func2 after the 2nd statement;
try
window.onload = function(){
func1();
func2();
}