setTimeout executes faster than simultaneous setInterval - javascript

So, I have a setInterval and a setTimeout running simultaneously in this click-o-meter thing I'm doing: the user enters an specified number of seconds he/she wants the game to run for, and then it counts how many clicks you have done, what was the average time between each click, and the average amount of clicks per second you've made during the specified period of time.
<html>
<head></head>
<body>
<input type='text' id='timerInput'></input>
<button id='btn'>Click</button>
<script>
var before;
var now;
var clicks = 0;
var cts = 0; //Stands for 'Clicks This Second'
var intervals = new Array();
var cps = new Array();
var cpsCounter;
var timer;
var canContinue = true;
var timerInput = document.getElementById('timerInput');
var timerTime;
var wasBad = false;
document.getElementById('btn').onclick = function() {
if(canContinue) {
if(clicks <= 0) {
if(timerInput.value.replace(/\D/, '') === timerInput.value) {
wasBad = false;
timerTime = parseInt(timerInput.value.replace(/\D/, '')) * 1000;
before = new Date();
cpsCounter = window.setInterval(ctsFunction, 1000);
timer = window.setTimeout(finish, timerTime);
}else{
alert('Only numbers please!');
wasBad = true;
}
}else{
now = new Date();
console.log(now - before);
intervals.push(now - before);
before = new Date();
}
if(!wasBad){
clicks++;
cts++;
}
}else{console.log('Game ended');}
};
function ctsFunction() {
console.log('Clicks this second: ' + cts);
cps.push(cts);
cts = 0;
}
function finish() {
console.log('Clicks: ' + clicks);
console.log('Average Speed (ms): ' + Math.floor(intervals.reduce(function(a, b){return a + b;}) / (clicks - 1)));
console.log('Average Speed (clicks per second): ' + (cps.reduce(function(a, b){return a + b;}) / cps.length));
intervals = new Array();
console.log('cps.length: ' + cps.length);
cps = new Array();
clicks = 0;
cts = 0;
window.clearInterval(cpsCounter);
canContinue = false;
}
</script>
</body>
</html>
So, the problem is that when the gmae finishes, that is, when timer reaches the end, ctsFunction() is supposed to run once more at the last second, so it can register data from it; but finish() is executed faster, or prior to ctsFunction(), thus clearing the cpsCounter interval and not allowing it to do anything on the last second. I've tried adding some extra milliseconds to timer, but if you choose to run the game for enough seconds, the same problem will eventually happen (e.g. if you add 1ms, the problem will be solved for up to 2 seconds, but not for more).

I have a setInterval and a setTimeout running simultaneously
It will never happens because javascript is a single thread language. There is no matter what is in your code, javascript can't execute two commands simultaneously.
And one more:
timer delay is not guaranteed. JavaScript in a browser executes on a
single thread asynchronous events (such as mouse clicks and timers)
are only run when there’s been an opening in the execution.
Read this article to understand how javascript timers work.

Related

Determining time remaining until bus departs

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");

Javascript score target alert

New to JS, please be nice.
In creating a Javascript score for a browser canvas game, the code below increases by 1 for each second. For the variable score to equal 100, how would I go about this function displaying a window alert for when it reaches this value?
Attempts similar to if(score == 100); alert(score) have not worked for me.
Below code will not currently work in JSFiddle, output displays in browser tab.
var start = new Date().getTime(),
score = '0.1';
window.setInterval(function() {
var time = new Date().getTime() - start;
score = Math.floor(time / 1000) ;
if(Math.round(score) == score)
{ score += '.0 Score'; }
document.title = score;
}, 100);
You might want to clear the interval when you are done. Otherwise the interval continues on executing and very soon the score is no longer 100 (or whatever the upper limit will be)
Something along the lines of:
var start = new Date().getTime(),
score = '0.1';
// get handle to interval function
var interval = window.setInterval(function() {
var time = new Date().getTime() - start;
score = Math.floor(time / 1000);
console.log(score);
if (score >= 5) { // set to 5 for speedier test/check
score += '.0 Score';
window.clearInterval(interval); // clear interval to stop checking
alert(score);
}
document.getElementById('title').innerHTML = score; // display it
document.title = score;
}, 100);
<div id="title"></div>

function to calculate function fps

Ok so I believe I could best describe the issue through code so here goes
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
//do stuff
}
Okay so to clarify I dont want to add a variable to the actual function clicking I would like to be able to call something like
FPS(clicking) and have the function return a value for example
var fps = FPS(clicking);
then i could display the returned number as such
element.innerHTML = fps
EDIT:
I know with the current code it seems silly but this is just example coding not what I am actually using
This is not very actual since Date.now() also uses time.
function FPS(fn) {
var startTime = Date.now();
fn();
var endTime = Date.now();
return endTime - startTime;
}
function longClick() {
var abc = 0;
for (var i = 0; i < 100000000; i++) {
abc++;
}
}
var fps = FPS(longClick);
console.log((fps / 1000) + ' seconds');
FPS usually refers to Frames Per Second which is the frequency of refreshing screen image.
Pick a more comprehensive name, with keywords like Elapsed, for teammates.
If you want to know "how fast the functions runs" :
/**
* Return the execution time of a function
* #param {Function} fn The function to execute
*/
function FPS(fn) {
var start = new Date().getTime();
fn();
var end = new Date().getTime();
return end - start;
}
You can have FPS return a DOMHighResTimeStamp (works in IE 10+, Firefox 15+, Chrome 20+, Safari 8+) which will return time in milliseconds. If you want it to work in older browser you can replace the precision timing with a Date (new Date()) object but the Date object will only nab you time in seconds (not milliseconds):
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
var start = performance.now();
fn();
return performance.now() - start;
}
console.log("Function took " + FPS(clicking) + " milliseconds!");
Here is some pseudo code to get what I think you're looking for - assuming you have a game loop and you're calling FPS in your game loop. As I said - more details about the specifics (such as components) of your game would be helpful.
var clicks = 0;
var fps = 0;
var elapsedTime;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
// Get start time
//call fn
// Get stop time
// var delta = stop time - start time
// elapsedTime += delta;
// fps++;
// If elapsedTime > 1 second
// then while elapsedTime > 1 second... elapsedTime -= 1 second and fps = 0;
// We use the while loop here in the event that it took more than 1 second in the call
// But you could just reset elapsedTime back to 0
}
This FPS(fn) would be called anywhere in your game in place of the original function to see how many times that function is called a second.
To answer the original question:
Okay so to clarify I dont want to add a variable to the actual function clicking I would like to be able to call something like FPS(clicking) and have the function return a value for example
Firstly you need to return a value from your clicking function, or any function you plan to pass to the FPS method.
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
return clicks;
}
Then in your FPS function, you need to return that value as well.
//function to calculate fps where fn is the name of the function
function FPS(fn){
//do stuff
return fn();
}

Capture photos in interval from canvas

I have a script that allows me to show in canvas the webcam and 'download' a specific frame within some intervals.
I am having trouble when time parameters are big (30 minutes of captures every 2 seconds). It works smoothly for about 15 minutes and then crashes (firefox closes with out of memory error). Also, after restarting firefox sometimes many 0 byte photos are taken during a 3-4 mins and then starts working again. I am running this in an old 2 GB RAM machine placed in the lab, is there a way to reduce memory usage?
Here is the piece of code with parameters and the function realizarCapturas.
I can add the resting code but I think the part to optimize should be this one.
var frecuenciaComienzoCaptura = 1; // how long till next capture
var frecuenciaCaptura = 3; //seconds between photos
var duracion = 5; // amount of photos to capture
function realizarCapturas(){
var i = 1;
var interval = setInterval(function(){
if(i <= duracion){
context.drawImage(video, 0, 0, 640, 480);
var imagen = document.getElementById("imagen");
imagen.href = canvas.toDataURL("image/png");
var now = new Date();
var filename = formatNumber(now.getHours()) + "-" + formatNumber(now.getMinutes()) + "-" + formatNumber(now.getSeconds());
imagen.download = filename + ".png"; // Make sure the browser downloads the image
imagen.click(); // Trigger the click
i = i+1;
}else{
clearInterval(interval);
}
}, frecuenciaCaptura * 1000);
}
setInterval(function(){
realizarCapturas();
}, frecuenciaComienzoCaptura * 1000 * 60 * 60);
realizarCapturas();
}, false);
As a rule NEVER use setInterval as it can be a source of call stack overflows which are very difficult to detect in code.
Your problem is that you are not clearing all the intervals you are generating and thus every 3 seconds you are creating a new interval event. Eventually the time it takes to run the little bit of code will be longer than than can be managed by all the interval events you have created and thus each interval will continue to push their events onto the call stack but will not get a chance to be run until more intervals have been place on the stack eventually causing the crash. Nor does setInterval guarantee the time between events are accurate.
Use setTimeout instead. That way you will only ever generate event as needed and you do not have to keep a handle to turn off events.
Below is your code written so that you will never have a call stack overflow.
var frecuenciaComienzoCaptura = 1 * 1000* 60 * 60; // how long till next capture
var frecuenciaCaptura = 3 * 1000; //seconds between photos
var duracion = 5; // amount of photos to capture
var counter = 0;
// the capture function
var captura = function () {
counter = counter + 1;
if(counter < duracion){ // do we need more images?
// only create timer events as needed.
setTimeout(captura, frecuenciaCaptura); //set time till next image
}
context.drawImage(video, 0, 0, 640, 480);
var imagen = document.getElementById("imagen");
imagen.href = canvas.toDataURL("image/png");
var now = new Date();
var filename = formatNumber(now.getHours()) + "-" + formatNumber(now.getMinutes()) + "-" + formatNumber(now.getSeconds());
imagen.download = filename + ".png"; // Make sure the browser downloads the image
imagen.click(); // Trigger the click
}
function realizarCapturas() {
// request next batch of captures by only creating one timer event as we need
setTimeout(realizarCapturas,frecuenciaComienzoCaptura);
counter = 0; // reset counter
captura(); // capture timages
}
// start captures.
realizarCapturas();

Avoid javascript's variables reset when user uses back and foward

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.

Categories

Resources