Javascript: How to speed up setTimeout function on website? - javascript

I am working on a website that asks me to complete a task, then once I complete that task it asks me to wait 1 hour before completing the next task.
What I am looking for here is to speed up the timer on this website instead of waiting for 1 hour.
How it works:
On Website I simply have to click on 'Roll' button then a timer start in descending order like (1:00)...(45:00)...(00:05) so on till it reach (00:00). Once it reach (00:00) it replace this timer to Roll button.
This timer only display Minutes and Second column.
It does not take computer time.
Changes I need:
Since it run in descending order or backward in seconds, I want to speedup this process so that instead of waiting for 1 hour I just have to wait for 20 or 30 minutes.
What I can't do:
Since this is a third party website so I cannot make changes in the website code I can only use browser console to run javascript code so I can override existing code on it.
Here is the Javascript for this timer:
<script>
$(function() {
$('#time_remaining').countdown({
until: +3600,
format: 'MS'
});
});
setTimeout(function() {
RefreshPageAfterFreePlayTimerEnds();
}, 3600 * 1000);
</script>

Looks like RefreshPageAfterFreePlayTimerEnds is global. So, you may try to override it like
var myTimeout = 3600; // 1 min
RefreshPageAfterFreePlayTimerEnds = function(speedUp) {
if(!speedUp) { // just to cancel "legal" call
return;
}
RefreshPageAfterFreePlayTimerEnds();
}
setTimeout(function(){ RefreshPageAfterFreePlayTimerEnds(true); }, myTimeout);

If you can't access to the website code, to change the code that doesn't allow you to reduce the time coding. You can change your IP address and use the website again.
If you have to sing in to use the website, forget, else you use another account and IP you will need to wait the time restricted to use again.

Related

Building an alarm clock style application

I am building a webapp (referred to as the "noticeboard") for a friend's business, to aid with their packaging and dispatch operation. It is built using HTML, CSS & JS. The backend is built in PHP / MYSQL.
The noticeboard is for the benefit of their staff and displays dispatch cut-off ("event") times, i.e as follows:
Dispatch Time 1 : 09:00
Dispatch Time 2 : 11:30
Dispatch Time 3 : 14:30
Dispatch Time 4 : 16:00
They update these times on a regular basis, as their schedule depends on their delivery firm's schedule. There is an AJAX request running every 15 mins which simply fetches the latest times (JSON format) from the database and updates the noticeboard. Although I could just simply implement an "auto browser refresh" every 15 minutes, I found this was a bit inconsistent and sometimes a "page cannot be found" error message would be displayed.
The noticeboard also displays a real-time clock. I have built this using moment.js.
The system runs 24/7 in a Chrome browser running on Windows 10. Nothing else is running on the machine.
At the moment the noticeboard simply displays these times. I need to take this one step further and make it function almost like an alarm clock. What I'm basically looking to achieve is 15 minutes before each event, it needs to highlight the upcoming event time (i.e. using jQuery addClass()). Then as soon as that event time is reached, play a buzzer sound (some kind of MP3 file). This needs to happen automatically every day for every event. Remember the event times are always changing, so it would need to be smart enough to recognise this.
What techniques can I use to achieve this functionality? I have been reading up on things like setTimeout() and setInterval(), however I'm not sure these are able to "auto-update" themselves once they have been set (i.e. if an event time changes). Do I need to look at a nodeJs based solution? I don't have any experience in nodeJs but if that's the best way to achieve this then I'm willing to give it a go. Otherwise I'm more than happy to try out something in vanilla JS.
Here's how I would approach it using setTimeout() but obviously this doesn't dynamically update:
// set the number of ms to 15 mins before the event time
var eventInterval = 36000000;
// setTimeout function for the event
setTimeout(function() {
// add "active" class to highlight the event
$('.event').addClass('active');
// after 15 mins have elapsed, remove the "active" class
setTimeout(function() {
$('.event').removeClass('active');
}, 90000);
}, eventInterval;
Your approach is fine, however, you need to do that EVERY TIME you get an AJAX response. setTimeout returns a timeoutId, which then you can use for cancelling the timeout with clearTimeout(timeoutId).
var reminderTime = 15 * 60 * 1000;
var timeoutIds = [];
function setTime(timestamp) {
// Set the interval 15 minutes before the event time.
var interval = timestamp - reminderTime;
var timeoutId = setTimeout(function() {
// add "active" class to highlight the event
$('.event').addClass('active');
// after 15 mins have elapsed, remove the "active" class
setTimeout(function() {
$('.event').removeClass('active');
}, 90000);
}, interval);
timeoutIds.push(timeoutId);
}
$.get("http://myserver/getTimes", function(times) {
// Reset all the setTimeouts
timeoutIds.forEach(function(timeoutId) {
clearTimeout(timeoutId);
});
// Assuming times is an array of timestamps
times.forEach(setTime);
});

how to exit php code after a few seconds?

I want to exit my php code after 10 seconds. Is there any possible way to do that? I have already found this code but it's not working.
set_time_limit(10); *//this line is blocked from the server*
ini_set('max_execution_time', 10);
Did you put set_time_limit at the begining of the script? if not - do it, because if you look at official documentation you will see next:
When called, set_time_limit() restarts the timeout counter from zero.
In other words, if the timeout is the default 30 seconds, and 25
seconds into script execution a call such as set_time_limit(20) is
made, the script will run for a total of 45 seconds before timing
out.
Also check it's return value:
"Returns TRUE on success, or FALSE on failure."
PS:
"The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real."
Does it help?
All written above you can find in http://php.net/manual/en/function.set-time-limit.php
I think that this code may help you:
$starttime = time();
do{
//make something
}
while ((time() - $starttime)<5); //stop with 5 seconds

Loop function for specified time, followed by delay

I have a small piece of code that continuously clicks a button called "See Older Messages" every 500 ms, in order to load infinitely-scrolled content from a webpage. Reasons for doing this are personal, but needless to say, I'm trying to automate something which would take me weeks of non-stop scrolling to do otherwise.
The problem is that the 500 ms delay gradually begins to drop as the script runs over time. After so many hours, it can take 5 seconds or more. I'm assuming this problem is caused by Facebook throttling my requests after so long, so to prevent this, I want to make the script run for an amount of time - say 2 minutes - followed by a delay of maybe 20 secs before it runs again for 2 mins, and so on. How would I go about doing this? I've racked my brains, but my limited knowledge of JavaScript hasn't come up with anything meaningful.
Below is the current code in its entirety.
setInterval(function () {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}, 500);
Thanks a lot in advance.
Keep track of when the script running started
While it's been less than 2 mins, keep clicking every 500ms.
After running for ~2 mins, stop and queue next run in 20s.
Go to step 2.
-
var lastChange;
function doClick() {
if (new Date() - lastChange < 120000 /* 2 mins */) {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
setTimeout(doClick, 500);
} else setTimeout(runScript, 20000 /* 20s */);
}
(function runScript() {
lastChange = new Date();
doClick();
})();
-
I recommend using setTimeout over setInterval since, if the browser takes a while to execute, loses focus and stops executing JS, gets paged out, etc., then you will still get the time spacing between events that you want. See https://stackoverflow.com/a/731625/1059070.
Toggle whether or not your function does anything by setting another timer.
/* When true do load else don't. */
window.doLoad = true
setInterval(function () {
if window.doLoad {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}
}, 500);
/* This will toggle doLoad every two minutes. */
setInterval(function () {
if (window.onLoad == true) {
window.doLoad = false;
} else { window.doLoad = true; }
}, 120000); // two minutes of milliseconds
In your case though you might be better off using the Facebook Graph API.
Graph API documentation from Facebook
Here's an existing question with the API using Python to do basically the same thing you want to do.
JS question, also similar

How do I programatically create a new Google Analytics session/visitor in javascript

I have an SPA that is running on a public computer. The app resets after a period of inactivity, and I would like any analytics that occur after the reset to show up as a different session/user. How can I do this?
I have tried deleting the __utm cookies (leaving __utmv), and further calls do show up as a different user, but I lose my custom variables for the first tracked event, whether I reset them right after deleting the cookie or right before tracking the next event.
It looks like switching to Universal and sending a sessionControl: 'start' field is the best I'll get.
In case anyone is looking for the answer to this in the future, here's how I've been able to achieve it...
// set the analytics session and visitor timeout to 10 milliseconds
_gaq.push(['_setSessionCookieTimeout', 10]);
_gaq.push(['_setVisitorCookieTimeout', 10]);
// make a fake page view, 10 milliseconds after this, the session will time out
_gaq.push(['_trackPageview', '/session/reset/']);
// after a short delay, set the analytics session and visitor timeout to 5 minutes,
// this should start a new session
setTimeout(function() {
_gaq.push(['_setSessionCookieTimeout', 300000]); // 5 minutes * 60 * 1000 = 300000
_gaq.push(['_setVisitorCookieTimeout', 300000]);
// log a page view...
_gaq.push(['_trackPageview', '/some/page/url/']);
}, 200);
... I'm not sure if that second page view is necessary or not (I needed it for my solution), but the cookie timeout updates seem to trigger a new session and visitor id
Also you might want to set the new timeout value to more than 5 minutes (the default is 30 minutes, or 1800000 milliseconds)

How to have a timer which cannot be modified in javascript?

Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());

Categories

Resources