I'm new to javascript, and I'm trying to see if what I want to do is possible. I want to take a current webpage that I have open in my browser, and execute new javascript. There is a timer on this page, and when it increases to a particular time, I want it to execute a button click.
This would be the time that is changing and that I want to add into a if statement:
07:34:04
Will this changing time raise an event that would cause a javascript to run? I want something along the lines of:
if time = 7:35:00 then click button.
Thanks for your help!
I'll like to make a contribution..
I don't know much about the javascript time format, but I'll post back if I can look it up.
Any way you can use a function such as this:
var waiter;
function waitForTimer(extime, fn)
{
//Here, fn is the function to be executed..
//While extime is the time at which the function is to be executed..
waiter = setInterval(function(fn,extime){
//this function will check every one second..
if( extime == time )
{
fn();
clearInterval(waiter);
}
else
log("waiting for " + time);
}, 1000);
}
I hope this helps.
Related
This is my school project. I have tried to do it as simple as possible, just to change background color in web page etc..
I work with an external device with two buttons (microbit a and b) -connected in serial port, writing data string "aa" or "bb". Then python code reads it inside for ever loop and writes it in json file, where this code should be able to enter in. With these changing json time stamps, this code should read which button was pressed latest and then do what is written in conditions.
json files reference time is changing all the time, by the button press.
I am very thankful for any help, we have been doing this project already quite long, this is final stage but as you see ,but i am not yet there.
As this does not execute anything after get json line... it did once, and till final >>if, but then it stopped..why? I dont know.. I am not good enough in this.
Final part of the code curly braces etc, i cant anymore count which one is too much or >>what is missing?! ...
my json example: {"REF": 1624391142, "aa": 1624391140, "bb": 1624391142}
$(document).ready(function () {
console.log("jQuery starts");
var d = new Date();
var time = d.getTime();
setInterval(function () {
// loop that reads every 2 sec json file,
$.getJSON("data.json"),
function (json) {
console.log("test", time);
//what is REF-time <= time
if (time <= json.REF) {
// any changes?
time = json.REF;
console.log(" REF", time);
pressedBtn = "";
jQuery.each(json, function (key, value) {
//searhing
if (value == time && key != "REF") {
pressed = key;
console.log("Working");
}
if (pressedBtn == "aa") {
$("body").show("active"); //background color change
console.log("pressed", pressedBtn);
$("#toshow").show("toshow"); // comment div
}
if (pressedBtn == "bb") {
$("#toshow").hide("toshow"); //comment div
console.log("pressed", pressedBtn);
}
});
}
};
}, 2000);
});
I think I understood you and maybe this is your solution check this
$(document).ready(function(){
setTimeout(doSomething,2000);
});
function doSomething(){
console.log("do something");
setTimeout(doSomething,2000);
}
this function is execute every 2 seconds like you want in your code
i hope i have help you
Ok, here is a pick what was wrong. I somehow had added parenthes there right side of the json, where is shouldnt be, thats how the whole block got stuck, i am appologising for taking anyones time. All these marks and syntaxes make one crazy..
Thank you anyway, this community is amazing
I am trying to program a little game that should reload after 5 seconds and tell people that they were too slow. Moreover, the variable points should be reset, so that they can start from new.
With
setInterval(function(){
window.location.href = "javascript:window.top.location.reload(true)";
}, 5000);
the whole website is loaded and people have to begin from scratch. The same happens when they press command+R.
I tried now to reset the variable points and show the alert that they were too slow.
setInterval(function(){
alert("You were too slow!");
points = 0;
}, 5000);
If I use this code, then the alert keeps on popping up very quickly. How can I reset everything and only get the alert every 5 seconds?
Depending on the browser the internal timer will continue running while the modal is displayed like in Firefox, or freez like in Chrome. So in Firefox if the modal stays open longer then 5 seconds, then the next one will be showed immediatily after the current one is closed.
There are only rare cases where you really want to use setInterval even if you have events that happen in regular intervals you most of the time should use setTimeout instead.
var roundTimeoutTimer;
function tookToLong() {
alert("You were too slow!");
points = 0;
}
function startTask() {
roundTimeoutTimer = setTimeout(tookToLong, 5000)
}
function finishedTask() {
clearTimeout(roundTimeoutTimer)
}
I have a game written in JavaScript and what it basically does is start a ten seconds timer and register the number of times the user is able to click on a certain button, before the timer elapses.
How the code works:
When a user clicks on the button, an element gets added to an array, using push function, then a different function returns the length of the array as the number of times clicked.
The problem with this:
If a user opens up the dev tools and alters the number of times an element is added to the array per click, this will change the outcome of the result.
My Approach:
What I decided to do is to store the length before I ran the push function and also after I ran the push function, then compare their differences and if it's greater than 1, it means something is not right. This seemed to work in my head until I wrote it down in code and discovered that if the user pushed multiple times before I checked the differences then it would go unnoticed. Please big brained guys, help me.
My code:
$('body').on('click', '.btn.z', function () {
// start listening
startCountingClicks()
})
var timerStarted = false;
var tc = [];
function startCountingClicks () {
$('.btn.z').html('ClickZed');
$('.Score').html('Your Score: '+gettc()+" clicks");
if (timerStarted == false) {
startTimer(10, $('#time'));
}
// user does multiple push before this function: startCountingClicks is called
var previous_length = tc.length; // get length before push
tc.push(1);
var new_length = tc.length; // get length after push
if (new_length - previous_length !== 1) {
console.log("fraud"); // this is supposed to catch a thief!!!
}
console.log(new_length+" "+previous_length);
timerStarted = true;
}
function gettc (){
// get number of clicks
return tc.length ;
}
A code that totally breaks this:
$('button').click(function(){tc.push(1); tc.push(1)})
EDIT:
I do not wish to protect against dev tools, though I am not against that method if it works. I just wish to get a better way of counting my clicks, a way that can't be affected by writing code on the dev tools.
You can't really stop people from doing stuff on the client side. It is pointless trying to prevent that. The best thing you can do is make sure whatever is sent matches what you expect on the server side.
I am coding a Greasemonkey script to click the play button for a script in Google Apps Script every five 5 minutes to avoid the execution time limit set by Google.
I was able to identify with the script when the time is over but am unable to click the "run" button by using JavaScript. I have been inspecting the button with Google Chrome and tried a few things but I couldn't make it work.
Can anyone please help me?
I guess clicking any button in the toolbar of Google Sheets would be exactly the same..
Thanks!
You are approaching this in a completely wrong way. You should be including the possibility to restart the execution with a trigger internally in your script. I will show you how I did it. Keep in mind that my script is quite large and it performs a loop and I had to make it remember where in the loop it stopped, so it could continue with the same data.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Purpose: Check if there is enough time left for another data output run
// Input: Start time of script execution
// Output: Boolean value if time is up
function isTimeUp(start, need) {
var cutoff = 500000 // in miliseconds (5 minutes)
var now = new Date();
return cutoff - (now.getTime() - start.getTime()) < need;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here the start is simply a new Date() that you create when you start the script. The need is simply an average time it takes for my script to perform 1 loop. If there is not enough time for a loop, we will cut off the script with another function.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Purpose: Store current properties and create a trigger to start the script after 1 min
// Input: propertyCarrier object (current script execution properties)
// Output: Created trigger ID
function autoTrigger(passProperties, sysKeys) {
var sysProperties = new systemProperties();
if (typeof sysKeys === 'undefined' || sysKeys === null) {
sysKeys = new systemKeys();
}
var triggerID = ScriptApp.newTrigger('stateRebuild')
.timeBased()
.after(60000)
.create()
.getUniqueId();
Logger.log('~~~ RESTART TRIGGER CREATED ~~~');
//--------------------------------------------------------------------------
// In order to properly retrieve the time later, it is stored in milliseconds
passProperties.timeframe.start = passProperties.timeframe.start.getTime();
passProperties.timeframe.end = passProperties.timeframe.end.getTime();
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Properties are stored in User Properties using JSON
PropertiesService.getUserProperties()
.setProperty(sysKeys.startup.rebuildCache, JSON.stringify(passProperties));
//--------------------------------------------------------------------------
Logger.log('~~~ CURRENT PROPERTIES STORED ~~~');
return triggerID;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yours can be more simplistic if you do not need to remember where you stopped (judging by your current implementation you do not care whether you start from the beginning or not).
The trigger you create should either aim at the main function or if you need to pass on the data like I do, you will need to have a separate starter function to get the data back from the user properties and pass it on.
I am trying to set a session timeout with Javascript and looks like the alert is blocking the timer from starting. Here is my code:
var first_timer = 2 * 1000;
var second_timer = 8 * 1000;
var down = -1;
function initTimer() {
down = setTimeout(processTimeout, first_timer)
}
function processTimeout() {
down = setTimeout(logout, second_timer);
alert ("Timeout of first timer, timerid:" + down );
}
function logout() {
alert("You are logged out");
window.location = "http://www.google.com"
}
function clearTimer() {
if ( -1 != down )
clearTimeout(down);
alert("Restarting timer");
initTimer();
}
initTimer();
When I run the above, I see the second timer only starts after the first alert is dismissed. How can I make sure the second timer starts immediately after first timeout even if the alert is not dismissed?
Thx
The alert() function blocks everything else until it is dismissed. You can use whats known as a modal dialog to create your own alert style message that does not block.
jQuery UI has this feature.
It most probably depends on the browser you are using. I'm not experiencing the issue you describe with latest Firefox.
But still, the second timer alert box won't be shown until the first one is closed.
This is because JavaScript interpreters are not multi-threaded. But JavaScript itself is heavily asynchronous, especially on long delay requests such as timers, AJAX and animations. This is what sometimes gives the feeling of multi-threading.
Indeed, in your code sample, the second timer started as expected. When I dismiss the first dialog box, let's say, 10 sec after it appears, the second one is immediately shown.
Nonetheless, and it may be your question, it will never be shown before you dismiss the first alert because alert is a synchronous call. So that the main event loop won't get the control back until dismissed.
A workaround for this situation is to use "HTML" dialog boxes as those provide by Jquery-UI for example.