There's a website that has a counter in it, just like file sharing sites that makes you wait till the count down finishes...well I just want to immediately set it to zero by a script or by using the Browser's Web Console or something...I just got the counter script from the source, and here is it:
var ms = 0;
var se = 17;
document.counter.d2.value = "17";
function d() {
if (ms <= 0) {
ms = 9;
se -= 1
}
if (se <= -1) {
ms = 0;
se += 1
}
else {
ms -= 1
}
document.counter.d2.value = se + "." + ms;
setTimeout("d()", 100)
}
d();
The count down time is about 17 secs (as you may have noticed in the code above). Well I tried to set the "se" (which means seconds in here) to zero with web console but nothing happens...Even I tried to set "document.counter.d2.value" to zero, nothing happens either....
Is there a way that can make this happen? Thanks in advance...
Related
For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.
I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.
I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.
Any assistance would be greatly appreciated.
UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!
var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];
var hFirst = shuttleOrange[0].slice(0,2);
var mFirst = shuttleOrange[0].slice(3,5);
var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);
var theTime = new Date();
var runFirst = new Date();
var runLast = new Date();
runFirst.setHours(hFirst,mFirst,0);
runLast.setHours(hLast,mLast,0);
if ((runFirst - theTime) >= (30*60*1000)) {
return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
} else if (theTime >= runLast) {
return "Orange Shuttle Service has ended for the day."
} else {
for(var i=0, l=shuttleOrange.length; i<l; i++)
{
var h = shuttleOrange[i].slice(0,2);
var m = shuttleOrange[i].slice(3,5);
var departPCN = new Date();
departPCN.setHours(h,m,0);
shuttleOrange[i] = departPCN;
}
for(var i=shuttleOrange.length-1; i--;)
{
//var theTime = new Date();
if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
}
var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);
if (timeRem >= 2) {
return "Departing in " + timeRem + " minutes."
} else if (timeRem > 0 && timeRem < 2) {
return "Departing in " + timeRem + " minute."
} else {
return "Departing now."
}
}
You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.
A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.
window.addEventListener('DOMContentLoaded', function() {
// Return time formatted as HH:mm
function getHHmm(d) {
return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
}
var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
"12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
"15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
var msg = '';
var msgEl = document.getElementById('alertInfo');
var time = getHHmm(new Date());
var index = 0;
// Set index to next scheduled time, stop if reach end of schedule
while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
++index;
}
function showNextBus(){
var time = getHHmm(new Date());
var schedTime;
// If run out of times, next scheduled time must be the first one tomorrow
if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;
// Otherwise, show next scheduled time today
} else {
// Fix index if rolled over a day
index = index % sched.length;
schedTime = sched[index];
msg = `Current time: ${time} - Next bus: ${schedTime}`;
if (schedTime == time) msg += ' DEPARTING!!';
// Increment index if gone past this scheduled time
index += time.localeCompare(schedTime) > 0? 1 : 0;
}
msgEl.textContent = msg;
// Update message each second
// The could be smarter, using setInterval to schedule running at say 95%
// of the time to the next sched time, but never more than twice a second
setInterval(showNextBus, 1000);
}
showNextBus();
}, false);
<div id="alertInfo"></div>
Edit
You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.
I have used filter for all shuttle left after the right time and calculated how much time left for the first one.
var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));
var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));
console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");
I'm attempting to generate a set of values every millisecond.
By using window.performance.now(), I've determined that 1000 points (1 second worth of data) requires approximately 1 millisecond worth of processing time.
So... why is a log statement generated every 3-ish seconds rather than every 1 second when my condition for generating the statement is that I have generated 1000 points?
The code is included below. And here is a link to jsfiddle: http://jsfiddle.net/MWadX/421/
var c = 0;
var m = 0;
var t = 0;
var x = 0;
var y = 0;
window.setInterval(function()
{
var e;
var s;
if (c === 0)
{
m = Date.now();
}
s = window.performance.now();
x += Math.random();
y += Math.random();
c++;
e = window.performance.now();
t += e - s;
if (c !== 1000)
{
return;
}
console.log(t.toFixed(0).toString() + " milliseconds");
console.log((Date.now() - m).toFixed(0).toString() + " milliseconds");
c = 0;
m = 0;
t = 0;
x = 0;
y = 0;
}, 1);
setInterval, setTimeout, and Minimum Timeouts
According to the Mozilla Development Network setInterval and setTimeout have a minimum timeout. This value varies somewhat between browsers, but the HTML5 spec specifies a minimum timeout of 4ms, and this value is pretty well respected in browsers made after 2010. If you pass a lower timeout, it will be internally inflated to the minimum.
Inactive Tabs
In background tabs, the timeout is restricted even further to a minimum of 1000ms.
I have a little jquery script for a stop motion animation. It uses moment.js to get the time and then does some math to get a "frame" number and then does some padding to match it to a filename in my directory, spits that into an img src and then iterates +1. I have two setInterval functions going-one that controls the frame rate (getframe) and one that controls how often the client checks for the proper time (gettime).
I've just discovered there are a bunch of dead frames in my directory though-- image files that I want to skip over but I can't just delete without screwing up my whole sequence, to be exact I want to my script to skip from image-029399.jpg to image-031170.jpg. Because a client might log in in the middle of that dead space, I was thinking I should have some kind of statement like if (frame>=29399 && <=31170; {frame=31171};) but I can't quite figure out how to insert that into my code without making everything stop working... below is my code:
window.onload = $(function () {
gettime();
setinterval(gettime,10000);
setInterval(getframe,580);
var frame;
function gettime() {
now = moment().zone('+0045');
if (now.hour()<=17) {
now =now.subtract('day',1)
}
if (now.hour() >= 18) {
now = now.subtract('hour', 18).subtract('minute', 30);
}
else {
now = now.add('hour', 6).subtract('minute', 30);
}
frame = ((now.hour() * 3600) + (now.minute() * 60) + now.second()) * 2 +7463;
}
function getframe() {
var framestr = frame? frame.toString() : "";
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
framerun = pad (framestr,6);
var src = "https://s3.amazonaws.com/combined11/image-"+ framerun +".jpg";
framerun1=parseInt(framerun);
$("#frame_placeholder").attr("src", src);
frame=framerun1 += 1;
}
});
Change it in the place where you set frame, i.e. gettime. Add this below your frame =... line:
function gettime() {
now = moment().zone('+0045');
if (now.hour()<=17) {
now =now.subtract('day',1)
}
if (now.hour() >= 18) {
now = now.subtract('hour', 18).subtract('minute', 30);
}
else {
now = now.add('hour', 6).subtract('minute', 30);
}
frame = ((now.hour() * 3600) + (now.minute() * 60) + now.second()) * 2 +7463;
if (frame >= 29399) {
frame += 1771;
}
}
Now, why?
First you change it where you're setting frame because it's the problem of the settor, not the gettor. And of course, since you're recalculating it each time, make sure you put the new code after the recalculation.
At first, I considered what you did: if (frame >= 29399 && frame <= 31170) frame = 31171;, but that essentially makes the program hang on the same frame for 1771 frames.
Then I considered if (frame >= 29399 && frame <= 31170) frame += 1771, but that's even worse - that would jump to the right frame, advance for 1771 frames, and then jump back to frame 31171, which isn't desired.
No, all you want to do is skip a gap, and all frames after that gap must make the same jump. So as soon as you hit the low side of the gap, just add the distance (31170 - 29399) of the gap to all values.
EDIT Actually, I don't know enough about the rest of your system to know if this is the right answer. If other things depend on the value of frame, you actually may want to make the change in the gettor without changing the base value of frame:
function getframe() {
var framestr = frame ? (frame >= 29399) ? (frame + 1771).toString() : frame.toString() : "";
And depending on what behavior you want in the deadzone, you may need to use any of the other function variations I discussed.
var framestr = frame? frame.toString() : "";
It looks like the top of getFrame would make the most sense, no?
function getframe() {
if (frame && ((frame >= 29399) && (frame <= 31170))) {
frame = 31171;
}
var framestr = frame ? frame.toString() : "";
// etc.
Well,
I Have a countdown timer, and I'm facing the following problem:
My countdown starts at 90 seconds. If the user waits until it reaches 2 seconds, for example, then he goes back using browser's button and after goes forward (backing to the same page), the countdown restarts at 90 seconds, not at 2 as I need, because when the timer reaches 0 I "click" at a button which post the form.
I know I need to handle the back and forward button and set my variable with the new value but I don't have any idea how can I do it. Any help will be great.
My code is below:
var count = 90;
var screenCount = count;
var newCount = 0;
function countFunction() {
if (screenCount != 0) {
var minutes = Math.floor(count / 60);
var seconds = count - minutes * 60;
if (count > 60){
if (seconds < 10)
seconds = "0" + seconds;
screen = minutes + "m:" + seconds + "s";
$('.timer').css('width',"120px")
}
else{
if (count < 10)
screen = "0" + count;
else
screen = count + "s";
$('.timer').css('width',"60px")
}
document.getElementById('tempo').innerHTML = screen;
if (count == 0) {
set('temporizador', screenCount);
$(":submit").removeAttr("disabled");
$('#responder').click();
}
if (count != 0) {
set('temporizador',screenCount - count );
count = count - 1;
setTimeout("countFunction()", 1000);
}
}
else {
document.getElementById('tempo').innerHTML = '∞';
set('temporizador', newCount);
newCount++;
setTimeout("countFunction()", 1000);
}
}
When the user presses back a whole new page is loaded, with an entirely new Javascript context. If you want to pass information from the context of one page to the context of another, there are several ways to do it.
In your particular situation, using LocalStorage is the easiest:
// count down 90 seconds, including page navigation on this site
var count = +localStorage.getItem('timerCount') || 90;
function countDown() {
count--;
localStorage.setItem('timerCount', count);
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
Suggestion by #DmitryVolokh
In this example i stored the remaining time in localStorage. If you want to track the elapsed time from a particular moment, you would be better served to store the starting time instead and compute the difference.
You use local storage for this as suggested above but there is the slight issue that some older browsers don't support localStorage: http://caniuse.com/#search=local%20storage
Since you are only storing a single number you could also use a cookie:
var match, count;
if (match = /timerCount=(\d+);/.exec(document.cookie)) {
count = match[1];
} else {
count = 90
}
function countDown() {
count--;
document.cookie = 'timerCount=' + count + ';';
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
You can use the onbeforeunload javascript event to see when the users leave the page, and then act as you want : changing the window.location to redirect the user (and give additional parameters like your timer), or prevent him from leaving the page.
You can also create a cookie or use localstorage to store the timer and get it back next time user comes to your page.
I have a really simple JS counter which I display on a dashboard like screen which does the following:
Every 5 minutes it makes an jsonp call and retrieves a "total" number
It then displays this number to the screen by incrementing the last total displayed till it is equal to the new total. (the number can only ever increase)
I'm having some trouble with making the number increment smoothly. What I would like to do is find a delta (i.e. New total - old total) and increment the number gradually over the 5 minutes till the next call so it looks like a nice smooth transition.
Any ideas on how I can do this?
Currently some of my code looks like this (This block get's called every 5mins. And yes, it's in dire need of a refactor...)
var LAST_NUMBER_OF_SESSIONS = null;
var five_minutes_in_seconds = 300;
var new_number_of_sessions;
$.getJSON('http://blah.com/live_stats/default_jsonp.aspx?callback=?', function(data) {
if(LAST_NUMBER_OF_SESSIONS === null){
LAST_NUMBER_OF_SESSIONS = data.total_sessions;
}
new_number_of_sessions = data.total_sessions;
var delta = Math.floor(new_number_of_sessions - LAST_NUMBER_OF_SESSIONS);
var time_interval = (five_minutes_in_seconds / delta) * 1000;
var old_value = LAST_NUMBER_OF_SESSIONS;
var new_value = null;
sessions_interval = setInterval(function (){
new_value = parseInt(old_value, 10) + 1;
$('#stats').text(new_value);
old_value = new_value;
if(new_value >= new_number_of_sessions){
clearInterval(sessions_interval);
}
}, time_interval);
LAST_NUMBER_OF_SESSIONS = new_value;
});
}
This code it seems to increment the number very quickly at the start of the 5min period and then stop so it's not exactly right...
Try this:
var total = 0,
delta = 0,
stats = $('#stats').text( total );
function increment() {
var v = +stats.text();
if ( v < total ) {
stats.text( v + 1 );
} else {
$.getJSON('http://...', function(data) { // added data here
delta = Math.floor( 300000 / ( data.total_sessions - total ) );
total = data.total_sessions;
});
}
setTimeout(increment, delta);
}
Update:
In order to test my code, I had to simulate the JSON reponse - I used an array of numbers. See here: http://jsfiddle.net/simevidas/MwQKM/
(In the demo, I use an interval of 5 seconds instead of 5 minutes.)
I am not exactly sure why your code doesn't work as expected, although I suspect that it has to do with line LAST_NUMBER_OF_SESSIONS = new_value;. I wrote something similar and it works fine. It's not that different from what you have, minus that last line of code.