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.
Related
I need to edit a few hundred or even a few thousand calendar events through Google Apps Script. It is about just minor changes to title (event.setTitle()) and description (event.setDescription()), nothing fancy. Trying with about 600 events the maximum execution time of 360 seconds is already exceeded.
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
for (var i = 0; i < events.length; i++) {
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
}
How to process the events in several chunks successively?
Answer:
Use PropertiesService to save where you got to so you can continue where you left of on next run.
Code:
You can use a PropertiesService key value pair to save the value of the count through events[]:
function renameEvents() {
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
var sp = PropertiesService.getScriptProperties();
if (!(sp.getProperty("count")) || sp.getProperty("count") == 0) {
var count = 0;
else if ((sp.getProperty("count") > 0) {
var count = sp.getProperty("count");
}
for (var i = count; i < events.length; i++) {
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
sp.setProperty("count", i)
}
}
It'll make the script a little slower, but each time you run it it'll continue along the calendar events from where the last one stopped.
References:
Class PropertiesService | Apps Script | Google Developers
I have previously used something similar to the following:
At the start of each loop check that a sufficient buffer time is available to complete the loop.
Update the buffer time whenever a single loop time exceeds it.
Use the PropertiesService to store both the buffer and the last index.
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
var ps = PropertiesService.getScriptProperties();
var startIndex = ps.getProperty('lastIndex') || 0;
var buffer = ps.getProperty('buffer') || 100;
var startTime = new Date();
var maxTime = 1000*60*6; //6 mins
for (var i = startIndex; i < events.length; i++) {
var loopStart = new Date()
if (loopStart - startTime > (maxTime-buffer) ) {
ps.setProperty('lastIndex', i);
break;
}
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
var loopTime = new Date() - loopStart;
if (loopTime > buffer ) buffer = loopTime * 1.5
}
ps.setProperty('buffer',buffer)
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.
I have found this script online and added my own images into it. The only problem is whenever I try to remove var seconds=Digital.getSeconds() it doesn't work anymore, meaning it stops updating.
However, when I keep the script in its original format, the clock does live update. How do I get the clock to update every minute? I only want the hours and minutes.
Here's the code in such a way that actually works properly (although I still don't like document.images... but it'll do)
var imgs = {}, i;
for( i=0; i<10; i++) {
imgs[i] = new Image();
imgs[i].src = "c"+i+".gif";
}
imgs.blank = new Image(); imgs.blank.src = "cb.gif";
imgs.am = new Image(); imgs.am.src = "cam.gif";
imgs.pm = new Image(); imgs.pm.src = "cpm.gif";
function extract(h,m,s,dn){
document.images.a.src = imgs[Math.floor(h/10) || "blank"].src;
document.images.b.src = imgs[h%10].src;
document.images.d.src = imgs[Math.floor(m/10)].src;
document.images.e.src = imgs[m%10].src;
document.images.g.src = imgs[Math.floor(s/10)].src;
document.images.h.src = imgs[s%10].src;
if( dn=="AM") document.images.j.src = imgs.am.src;
else document.images.j.src = imgs.pm.src;
}
function show3(){
var Digital = new Date(),
h = Digital.getHours(),
m = Digital.getMinutes(),
s = Digital.getSeconds(),
dn = h >= 12 ? "PM" : "AM";
extract( h%12 || 12, m, s, dn)
setTimeout(show3,1000);
}
Now, if you want to get rid of seconds, comment out these lines:
// document.images.g.src = imgs[Math.floor(s/10)].src;
// document.images.h.src = imgs[s%10].src;
And remove the g and h images from your HTML source.
You can't remove the seconds, they're needed to increase minutes every 60 seconds. But you can choose not to display them.
But considering the script, you would have a better result making yourself the script, using setInterval and Date as A1rPun said.
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! :)