How to make stopwatch synchronized with server in javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am currently working on a game in which a timer will be needed, but the one made in js has a very long delay and on each device it is different, which in the case of a ranking where milliseconds count is unacceptable.
I want to create a stopwatch that will be synchronized with the server time and will have the smallest local delay and will show the elapsed time with an accuracy of 0.01 seconds. Any idea how i can do this?
My code look like this:
var stopper = setInterval(myTimer, 10);
let time = 0;
let run = true;
function myTimer() {
if(run) {
time += 0.01;
//update time display
}
}

You can keep something startTime on the server and use on the client to calculate passed time.
If you need to keep the time and update necessarily then try to use websocket

Related

How to make a variable increase or decrease exponentially in a for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to increase or decrease a variable in a exponential or speeding up manner in a piece of code that happens every frame.
This code gets executed every frame:
if (animationLenght > 1) {
animationLenght --
// implement speeding up value
...
}
Doesn't have to be exponential exactly but like that it accelerates (or decelerates)
The animation variable decreases linearly by one on every frame.
I want to increase or decrease a value in an non linear fashion, but like speeding up or slowing down smothly.
Any ideas?
You can check the Math.exp() function: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/exp
let expNum;
for(let i=0; i < length; i++){
expNum = Math.exp(i)
}

Javascript method to alert the user when a method is taking longer than expected? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have some socket.io emits that I'd like to provide handling for when they are taking too long to get back from the server with their promise. But I also don't want to outright time them out. I have seen this on some websites where a loading spinner will add 'This seems to be taking longer than usual' text after 10 or so seconds.
How can I add a timeout-style method to a Javascript function that will do something after a certain amount of time, but will NOT cancel the original method?
Unless you have a global scope, you'll need to pass in two handlers
Something like this (I've generalised the flow because you've not provided enough information about your existing set up, so I hope it makes sense)
function doSocketRequest(normalHandler, tooLongHandler) {
let timer = null;
// set timeout to 5 seconds, if we hit it then trigger "tooLongHandler"
timer = setTimeout(tooLongHandler, 5000);
// When we receive our socket response for the event, clear the time and trigger "normalHandler"
socket.on('some_event_response', (response) => {
clearTimeout(timer);
normalHandler(response)
});
// Emit to server
socket.emit('some_event', ...etcetc);
}

server side timer on every 3 minutes in current timer for a bet making game node js with unique game id [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
sample picture i am creating a bet game in node js back end and angular for front end where number of users can choose any number from current game and after timer end they will get result and reward point. After game end, timer is restart from 3 minutes with new game. And if new user will come here, he can see real time left of game. What is best logic to get this approach?
i added UI of my game in link.
When you set the timer, you could calculate the game end time and then send it to the client... For example, if the game starts at 14:30:05, you send 14:33:05 to the client. I recommend you a library called MomentJS
let endTime = 0;
let timer;
function startGame() {
endTime = moment().add(3, 'minutes'); // Current time + 3 minutes
console.log('game started at', moment.now())
}
function renderTimer() {
// This goes on the client side
clearInterval(timer); // If you hit start game again you need to clear the loop
timer = setInterval(function(){ $('#h1').text(moment(moment(endTime).diff(moment())).format('mm:ss')); }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- MomentJS -->
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<button onclick="startGame()">Start game</button>
<button onclick="renderTimer()">Get timer</button>
<h1 id="h1"></h1>

Simple Javascript timer with system date [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to make a javascript timer for a countdown of 7 days since it is first run.
Here is the scenario:
The html file will given to 100 students
So the timer will start whenever one opens the html file
If the user restarts the computer the time will not affect
Dont know how its done..
The simplest possible JavaScript countdown timer?
This can be accomplished locally (that means that each user gets their own counter) by saving the value of Date.now() into localStorage. Then, when reopening the html file, you read from localStorage and compare the value to the current Date.now().
What you can do with this timer is then very limited, unless you serve this html file of yours from a server.
(function() {
var started = localStorage['started'];
if (started) {
// This is not the first time the user opens this file
// How long has it been?
var diff = Date.now() - started;
if (diff >= 1000 * 60 * 60 * 24 * 7) {
// At least one week has passed. Do something here.
} else {
// Less than a week has passed. Do something else here.
}
} else {
// This is the first time the user opens this file
localStorage['started'] = Date.now();
// Do something else here to welcome the user...
}
})();
Date.now reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
Just remember that there is no security at all in this. You are doing this on the user's browser, and the user has full control over that environment. A simple clear cache will delete the saved value from localStorage.
I have used this method to create a project time clock that runs completely locally.

Updating image on sunset/sunrise [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Okay guys, I got a page, displaying 24/7, I got sunrise/sunset time that I'm getting from server (websockets, there is much more data, lets stick to this) and I got images of sun/moon.
What is the best way to change image on page, depending on daytime?
The point is: when image updating function should be called? Each day I should get new values, but I can't predict the time when I'll get those. If I will use delayed timers, how should I get timers updated, when I will recieve new sunrise/sunset time?
Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Timers. You can set a relative timeout by first determining what time it is, and using the offset to sunrise/sunset.
I think you can create a timer on your page which check the time of day every period of time (10 minutes) and compare it with the dates you got from server.
$(document).ready(function(){
setInterval(check_dates,60000);
});
function check_dates()
{
var now = new Date();
if(now>=sunrise_datetime && now< sunset_datetime)
{
$('body').html('<img src='sunrise_image.jpg' />');
}
else
{
$('body').html('<img src='sunset_image.jpg' />');
}
}

Categories