Game time in Javascript Browser Game - javascript

I'm fairly new to javascript and programming at all, to be honest. I know html and css and the basics of javascript and I'm trying to figure out how time works in js.
I would like to make a simple game where the user can take care of a horse. And every action he does (i.e brushing the mane) would take a specific amount of time. Let's say five minutes for that. How do I code that?
Would be really thankful if anyone could tell me. Thank you in advance.
Jolly

just get the time in the future when the even would be finished at.
use this function
function getTime(numOfHours) {
let date = new Date();
date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000);
return date;
}
then do check in your game logic to see if the event end time against the current time.
let endEventTime = getTime(0,00138); // add 5 seconds to the current time
// do a loop or some setTimeout() login and once the time passes then let your user do another action.

Related

JavaScript function to run everyday at 6:30pm EST

I have written a JavaScript function that I simply copy paste into a browser console and runs, all works great and is working exactly as I want it to.
Looks like:
function test(d) {
// ....
}
test(num);
I'm looking to wrap this function with kind of like a "while" statement. Please do keep in mind I'm not the greatest with JavaScript, yet.
Basically, What I'm looking for is while its NOT 6:30PM EST... keep waiting and check again. The second it hits 6:30 PM EST, execute the script.
Can anyone help me with what the syntax would look like? I found a lot on Stack Overflow but the syntax isn't really making sense to me.
Any help would be greatly appreciated.
Okay, a couple of notes. If you're not required to run a script in the browser itself but simply run some JavaScript at specific intervals you should checkout some schedulers like cron and more specifically for JavaScript - node-cron.
A solution which revolves around checking "is it time, is it time,..." each second or so in a loop is a pretty bad way to do it.
It is highly wasteful and poorly performant.
It will block your script execution so you have to execute it in a separate process like a web worker.
The simplest way, without using any dependencies is to schedule your work manually using a combination of setTimeout and setInterval. Here is a pretty basic and unpolished solution which should get you going.
const msInSecond = 1000;
const msInMinute = 60 * msInSecond;
const msInHour = 60 * msInMinute;
const msInDay = 24 * msInHour;
const desiredTimeInHoursInUTC = 18; // fill out your desired hour in UTC!
const desiredTimeInMinutesInUTC = 30; // fill out your desired minutes in UTC!
const desiredTimeInSecondsInUTC = 0; // fill out your desired seconds in UTC!
const currentDate = new Date();
const controlDate = new Date(currentDate.getUTCFullYear(), currentDate.getUTCMonth(), currentDate.getUTCDate(), desiredTimeInHoursInUTC, desiredTimeInMinutesInUTC, desiredTimeInSecondsInUTC);
let desiredDate;
if (currentDate.getTime() <= controlDate.getTime()) {
desiredDate = controlDate;
}
else {
desiredDate = new Date(controlDate.getTime() + msInDay);
}
const msDelta = desiredDate.getTime() - currentDate.getTime();
setTimeout(setupInterval, msDelta);
function setupInterval() {
actualJob();
setInterval(actualJob, msInDay);
}
function actualJob() {
console.log('test');
}
In short, it calculates the difference between the current time and the next possible upcoming time slot for execution. Then, we use this time difference to execute the desired task and further schedule executions on every 24h after that.
You need to provide values for desiredTimeInHoursInUTC, desiredTimeInMinutesInUTC and desiredTimeInSecondsInUTC. All of them should be in UTC (the normal difference between EST and UTC is -4 or in other words - (hour EST - hour UTC = -4). You can (and actually should) improve this solution to handle timezones and the time difference calculations in general more elegantly.
A caveat here is that it won't handle daylight saving for you so you should keep that in mind. You can tackle this easily by using a dedicated library like moment.js. Also, the code is simple and in this version doesn't support cases like skipping specific days and such. You can always extend it to handle those, though.
Lastly, every time you restart the script, it will schedule your function execution times properly so you don't need to keep your tab open at all times. As an added benefit, the solution is quite performant as it doesn't do checks continuously if the time for execution has come but schedules everything in advance and doesn't do any more checks after that.

Javascript countdown - not counting down

I have a countdown script that gets the live time and subtracts it from a set time. It all works apart from the fact that it doesn't update unless you refresh your page. The setInterval at the bottom of my function instructs the function to run every one second, but it doesn't seem to be doing that...
Can anybody help?
Here is my jsfiddle: http://jsfiddle.net/4yMZy/
Each time cCountDown runs, its is calculating the time left like so:
nDates = new Date(datetime);
xDay = new Date("Fri, 26 May 2012 16:34:00 +0000");
timeLeft = (xDay - nDates);
The value of datetime there never changes from one run to another. So cCountDown is constantly running, but is always comparing the difference between the same two dates. Since the same two dates are used, the difference is always the same, so you do not see any countdown occur.
You could change nDates = new Date(datetime); to nDates = new Date(); and it will start counting down, but I am not sure why you are getting datetime from some server in the first place.
There are some other issues with your code as well. You should run it through jslint or jshint.
If changed your code to http://jsfiddle.net/4yMZy/7/
So it fetches the time and updates the seconds according to the set interval.
Edit:
jsfiddle actually provides a button for that on the top.

JavaScript: Is this timer reliable?

Today I was introduced to the world of Web Workers in JavaScript. This made me rethink about timers. I used to program timers the ugly way, like this.
var time = -1;
function timerTick()
{
time++;
setTimeout("timerTick()",1000);
$("#timeI").html(time);
}
I know this could be improved by saving the date when you start the timer, but I've never been a fan of that.
Now I came up with a method using Web Workers, I did a little benchmark and found it much more reliable. Since I am not an expert on JavaScript I would like to know if this function works correct or what problems it might have thanks in advance.
My JavaScript code (please note I use JQuery):
$(function() {
//-- Timer using web worker.
var worker = new Worker('scripts/task.js'); //External script
worker.onmessage = function(event) { //Method called by external script
$("#timeR").html(event.data)
};
};
The external script ('scripts/task.js'):
var time = -1;
function timerTick()
{
time++;
setTimeout("timerTick()",1000);
postMessage(time);
}
timerTick();
You can also view a live demo on my website.
If you're trying to reliably display seconds ticking by, then the ONLY reliable way to do that is to get the current time at the start and use the timer ONLY for updating the screen. On each tick, you get the current time, compute the actual elapsed seconds and display that. Neither setTimeout() nor setInterval() are guaranteed or can be used for accurately counting time.
You can do it like this:
var start = +(new Date);
setInterval(function() {
var now = +(new Date);
document.getElementById("time").innerHTML = Math.round((now - start)/1000);
}, 1000);
If the browser gets busy and timers are erratically spaced, you may get a slightly irregular update on screen, but the elapsed time will remain accurate when the screen is updated. Your method is susceptible to accumulating error in the elapsed time.
You can see this work here: http://jsfiddle.net/jfriend00/Gfwze/
The most accurate timer would be a comparison of two time stamps. You could increase the precision of your timer by updating more frequently (such as every 100ms). I prefer using setInterval() over setTimeout().

Getting certain frequency with setInterval method

In a javascript code I develop, some function should be called every 1 second. But to be sure that this operation takes place every 1 second, the following code is utilized:
setInterval(doIt, 500);
function doIt() {
var now = (new Date()).getTime();
if(lastUpdate + 1000 >= now) {
/// code...
lastUpdate = now;
}
}
As far as I know setInterval(doIt, 1000) doesn't always mean that it's called every one second.
Is the above solution is a valid one? If not, what do you recommend?
You could use setTimeout instead of setInterval, and make dynamic adjustments each time your function is called. The idea is to set the timeout for a number of milliseconds sufficient to carry you to the next second boundary.
function timeoutFunc() {
// do interesting things
var time = new Date().getTime();
setTimeout(timeoutFunc, 1000 - time % 1000);
}
You'd start it off with:
setTimeout(timeoutFunc, 1000 - new Date().getTime() % 1000);
Synchronizing with the server seems like a bad idea, because you have no way of knowing whether the client clock is synchronized to anything (like the NTP server network). If it's not, then you server synchronizations are going to make things look wrong at the client, because the client clock will always be what seems right.
well setInterval IS defined in milliseconds. so it means its called every X millisdconds.
however the system can freeze or something like that!
but theres no practical better solution, you approach is fine.
if you really have an extensive javascript client application the results could stretch a little bit.
a possible solution for that is to get the system time and have a counter in your function. then ever X executions you align with the system clock, calculate how many function calls you should have until now and speed up the interval or slow it down.
this is as far as you can get to perfection. but it will be only a matter of milliseconds and probably not worth the effort.
may i ask what you are developing?

Counting down for x to 0 in Javascript?

I have from the backend a time on the format 00:12:54 and I display it to the screen. But, I would like to have this time to continue to go down. I have though to create a variable in javascript that will old the time and with setTimeout to loop to display with document.getElementById the new value. I think it can be problematic if I have many time to go down in same time. I might require an array?
How would you do that? If I have no other suggestion, I will try my way, but I am curious to know if it does have a more secure way to do it.
Do you know jQuery Framework? It's a Javascript framework that have a lot of utilities methods and functions that let you do Javascript stuff more easily.
Here is a count down plugin (haven't tested it).
I suggest you to download JQuery than download the plugin . Check the sample of code from the "relative" tab on the website. You can have something like :
$('#until2d4h').countdown({until: '+12M +54S'});
*The only drawback with what I suggest you is that you will require 2 .js to be added. Try to add them only when needed and you will be find.
General algorithm:
Read time from server.
Read the current time.
Call a function.
In your function, read the current time, get the delta from the initial time you read in step 2.
Subtract the delta from the initial time you read from the server in step 1 and display the remainder.
The function should call window.setTimeout to call itself in 1000ms (or adjust according to time elapsed within the function), if you want to continue counting down.
Here's a rough cut:
window.onload = function () {
var countdown_start_in_ms = 6000; // from server
function tick() {
var now = new Date().getTime();
var disp = start - now;
if (disp < 0) {
disp = 0;
}
var el = document.getElementById("countdown");
el.innerHTML =
// quick hack to format time
/(\d\d:\d\d:\d\d) ...$/.exec(new Date(disp).toUTCString())[1];
if (disp > 1000) {
var elapsed = new Date().getTime() - now;
window.setTimeout(tick, 1000 - elapsed);
} else {
// stop countdown and set color to light grey
el.style.color = "#ccc";
}
}
var start = new Date().getTime() + countdown_start_in_ms;
tick();
}
You won't like the taste of this one, but it'll do you good:
Google for 'javascript timer' and get your hands dirty reading through the various examples and tutorials returned by that search.
You'll learn a lot more than just how to write a count-down timer. :-)
Good luck!
Take a look at Grab hands and set your own time. and inspect its code. While it is written with Dojo, the "clock" part is in plain JavaScript. In your case the only difference is how to advance the counter — decrease rather than increase it.

Categories

Resources