How to make a countdown timer for 5 second countdown? - javascript

I am making a game where there is a 5 seconds countdown, I am doing this countdown on the server side. I want the timer to start over and over again when I send it the request it will respond with the current timer value. For example if 2.2 seconds has passed when the request is made it sends 2.8 seconds as a response and so on. Below you can see my code at the moment, thanks in advance!
router.get("/:result", (req,res) =>{
const result = JSON.parse(req.params.result)
var timerTime = {
time: null
}
if(result.message == "startNewTime"){
//Start the timer
}else if(result.message == "checkingTime"){
//Get the timer value and set it to be the timerTime.time value
//Start the timer from 5 seconds again
res.send(JSON.stringify(timerTime))
}
})

Have you tried setTimeout() ?
You can pass the function or result as first argument and milliseconds as second parameter.
Then you can approach it differently! Try setting a simple counter.
let counter = 0
for(let i = 0; i < 5; I++){
setTimeout(counter++, 1000)
}
Maybe it works this way? You can only track seconds this way though, not milliseconds.

I got it working. The problem I had with the date.now() method was that I was sending a new request and the variable value reset ofc so I just saved it to the session and got it working. Thanks bye!

Related

Only execute a function once in a given amount of time

I have an api request that is called multiple times in a given amount of time. More specifically this request is for refreshing the user token, so it's called on every request, which adds up pretty quickly. I would like to create a function that tells the function not to run for a given amount of seconds. I have tried using lodash debounce but I can't get it to work.
let debounceRefresh;
debounceRefresh = debounce(() => {
api.request(){
});
}, 1000);
debounceRefresh();
Am I executing this wrong? Is it possible to do?
Yes, you definitely need throttle for the job.
// in this example we invoke a fn for a period of 10 sec, invoking it 2 times a second, but we can perceive that the original function is only invoked at most once per 2 seconds according to the parameter below:
var TOTAL_TIME_TO_RUN = 10000; // 10 sec
var THROTTLE_INTERVAL = 2000; // <= adjust this number to see throttling in action
var INVOCATION_INTERVAL = 500; // 0.5 sec
// regular fn
var punchClock = function punchClock() {
console.log(new Date().toISOString() + ' - call api');
};
// wrap it and supply interval representing minimum delay between invocations
var throttledPunchClock = _.throttle(punchClock, THROTTLE_INTERVAL);
// set up looping
var intervalId = setInterval(function() {
console.log("attempting call api");
throttledPunchClock()
}, INVOCATION_INTERVAL);
// run the demo
setTimeout(() => clearInterval(intervalId), 10000)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>
<pre>
var TOTAL_TIME_TO_RUN = 10000; // 10 sec
var THROTTLE_INTERVAL = 2000; // < = adjust this number to see throttling in action
var INVOCATION_INTERVAL = 500; // 0.5 sec
</pre>
Snippet from github
Have you tried with a timeout?
const myTimeout = setTimeout(debounceRefresh, 1000);
If the function is called again, you can clear the timeout and reset it
clearTimeout(myTimeout);
Why don't you use a different listener? Perhaps when data is received?

How to configure my method to call after x seconds?

I want to start timer after x interval seconds.This x interval seconds will come from server side.
Now i have some process going on server side and on page load i call getData method which starts a timer based on isRunning flag and i display progress
untill i found isRunning false and then stop a timer.
So if user is already on my page where i have 1 schedule jobs which will run after x seconds so i want this getData to call after that x seconds.Right now once user comes on the page getData keeps on going server side for getting progress for schedule jobs.
Hence i was thinking that i will get total seconds of first schedule job and configure my timer to start getData method after x seconds if user doenst refresh the page.
But here i am not getting how to configure $scope.startTimer method in such a way that it will start after x seconds.For eg:If schedule job will run after an hour then start timer method should only start after 1 hour and keep calling getData method every 2 seconds.
Below is my code:
function getData() {
myService.get(function (response) {
if ($scope.isRunning)
$scope.startTimer();
else
$scope.stopTimer();
//response.totalSeconds;here i will get total seconds after which i want to call this method again to show progress of schedule job
});
}
var stop;
$scope.startTimer = function () {
// Don't start a new timer
if (angular.isDefined(stop)) return;
stop = $interval(function () {
if ($scope.refreshTimer > 0) {
$scope.timerLabel = false;
$scope.refreshTimer = $scope.refreshTimer - 1;
} else { //REFERSH CALL
$scope.stopTimer();
getMockProgress();
}
}, 2000);
};
$scope.stopTimer = function () {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
};
Update :
else
$scope.stopTimer();
if (response.milliSeconds > 0)
setTimeout($scope.startTimer, response.milliSeconds);
But this fails to call startTimer method after x milliseconds.
I will appreciate any help :)

Javascript: Know when an actual second is ticked?

I have a setInterval function, which displays the remaining time for an event on my website. But the countdown is not in sync with the actual tick of the second.
My code uses an ajax call to the server to get the expiry date once, and on its success the countdown will start. Great till there.
var request = new XMLHttpRequest();
request.open('GET', 'https://my-website/service.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
date = request.responseText;
timer = setInterval(showRemaining, 1000);//start the countdown
} else {
// We reached our target server, but it returned an error
}
};
But the time when setInterval is called needs to be in sync with actual global tick of the second.
(I hope I make sense. I mean the calls need to be in sync with each time a second passes in your PC's or phone's clock!)
How can I achieve that? Thanks in advance!
You need to make an initial setTimeout with the difference between the current ms and the next ms, ie:
1000-(new Date().getMilliseconds()))
then you can start the setInterval
Note that setTimeout/setInterval has a minimum value (generally considered 10ms), so if it's less than that value to the next second, add 1000.
Also note that setTimeout/setInterval are not 100% accurate, but for the nearest second will likely suffice.
This gives your success code:
date = request.responseText;
var t = 1000-(new Date().getMilliseconds());
if (t < 15) t+=1000;
setTimeout(function() {
timer = setInterval(showRemaining, 1000);//start the countdown
}, t));
As #freedomn-m suggested in the comments, 1000-(new Date().getMilliseconds()) is the key piece of code I was looking for - the difference between the current ms and the next ms. So my code is now working and it looks like this:
if (request.status >= 200 && request.status < 400) {
date = request.responseText;
setTimeout(function() {
timer = setInterval(showRemaining, 1000);//start the countdown
}, 1000-(new Date().getMilliseconds()));//to make the calls in sync with actual tick of the second
}

JS variable containing ongoing time value

I'm working on a chatbot script (Hubot - running in terminal) exercise and looking for a method to count the time since the last message was left in the thread. Then after nobody has left a message for X number of minutes (let's say 10,000 milliseconds) I would like to console.log("CRICKETS!..CRICKETS!..")
I'm imagining something like:
//currentTime - startTime = timeSince
//and
// if( timeSince > 10,000)
// {console.log("Crickets!..")
however I'm not sure of how to create the currentTime variable as continuously growing counter
Below is the code I've started which doesn't appear to throw any errors in the , but also doesn't seem to work as I'm running it in the terminal. It just prints the current time twice
module.exports = function(robot) {
return robot.hear(/$/i, function(msg) {
var startTime = (Date.now()) ;
return(startTime);
if (Date.now() - startTime > 1000) {
console.log("CRICKETS..!...")
};
});
};
You'll notice I'm using Date.now() but I'm not attached if there's a better method. Also here is a link to basic hubot scripts in case it is needed for context - https://github.com/github/hubot/blob/master/docs/scripting.md
You can always use setTimeout and cancel it if need be
Pseudo-code:
var myTimeout = setTimeout(function () {
//nobody has left a message for 10 seconds
}, 10000);
if (user has left message)
clearTimeout(myTimeout);
The window.setTimeout function allows you to trigger a callback function after a delay. And you can clear that timeout by calling window.clearTimeout(value_returned_by_setTimeout).
We could define a callback: function crickets(){ console.log('Chirp! Chirp!'); }
Assuming some function newMessage gets called whenever a a new message appears, you could try something like this:
var cricketTimeout = null;
function newMessage(){
//... your code
if (cricketTimeout) clearTimeout(cricketTimeout);
cricketTimeout = setTimeout(crickets, delayInMilliseconds);
}

How can I start and stop multiple JavaScript timers?

I want to run a timer in JavaScript for 30 seconds, play a beeping .WAV file, then count 10 seconds and play the beep again. I want this to repeat until either a desired time is hit or the user intervenes and clicks a stop button.
This is how I've implemented it:
function startWorkOut(param) {
if (param === 1) {
setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
The problem is I don't know how to stop it. Because these two functions are calling each other back and forth, I need to know how to put in some sort of a manual break.
Assign it to a variable
var beepTimer = setTimeout(playBeep, 30000); //30 second workout
clearTimeout(beepTimer); // This will clear that timer
Try this;
var timerConst;
function startWorkOut(param) {
if (param === 1) {
timerConst = setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
timerConst = setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
function stop(){
clearTimeout(timerConst);
}
Store the reference returned by setTimeout or setInterval method and then use window.clearTimeout or window.clearInterval to remove those timers. Example:
var ref1 = window.setTimeout(function() {your code}, 5000);
var ref2 = window.setInterval(function() {your code}, 5000);
An then remove them using the following code:
window.clearTimeout(ref1);
window.clearInterval(ref2);
Hope it help.
jsFiddle Demo
"I want to run a timer in JavaScript for 30 seconds, play a beeping .WAV file, then count 10 seconds and play the beep again. I want this to repeat until either a desired time is hit or the user intervenes and clicks a stop button."
Timers are 3 and 1 second for brevity
var playing;//variable for timer
function startWorkOut(){
var entry = playing === void 0;//true if playing is undefined
var interval = entry? 3000 : 1000;//first entry is 3s timer, others are 1s
if(!entry)playBeep();//play a beep except when the workout timer is first started
playing = setTimeout(startWorkOut,interval);//play a beep in either 3s or 1s
}
function stopWorkOut(){
clearTimeout(playing);//stops timer
playing = undefined;//restores variable state
}

Categories