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 :)
Related
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!
In my app, I need to run my app offline because drivers have to use that app and in remote areas, they might not find internet for that purpose I need to download all data in advance through Axios request at the time they have internet. so that request can get data from the cache instead of server.
At the moment i tried this but this doesn't seems to be good practice
tryOffileWorkSheet: async function () {
Network.addListener("networkStatusChange", (status) => {
if (status.connected) {
setInterval(function () {
let worksheet = JSON.parse(localStorage.getItem("worksheet"));
if (worksheet == null) {
worksheet = [];
}
// localStorage.removeItem('worksheet')
for (let i = 0; i <= worksheet.length; i++) {
if(worksheet.length > 0){
setTimeout(function () {
if(worksheet[i]?.work_order_id){
ApiService.get(
`/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
).then((response) => {
if(response.data.status){
worksheet.splice(i,1)
localStorage.setItem("worksheet", JSON.stringify(worksheet));
}
console.log('After', worksheet)
// this.closeModal();
});
}
},i* 3000);
}
}
}, 3000);
}
});
},
also for this, it is necessary for the user to behave on this page when the internet available it means that we need to download a lot of data.
Can you please tell me the best practice to do that or plugin for vue which can help for that
The question is sort of unclear and is not maybe the best fit for SO, but I'll try to answer.
The first thing I noticed here is the use of setInterval, not that you are using it, but rather how. There's nothing that stops the interval from running. Here's a scenario that I hope illustrates the problem
networkStatusChange fired: status.connected === true
setInterval creates interval #1
3 seconds later interval #1 fires
... this keeps happening for the next 2 hours
networkStatusChange fired: status.connected === false
... interval#1 keeps firing
networkStatusChange fired: status.connected === true
setInterval creates interval #2
within 3 seconds interval #1 fires
3 seconds later interval #2 fires
... intervals #1 and #2 keep firing (twice within 3 seconds)
networkStatusChange fired: status.connected === false
networkStatusChange fired: status.connected === true
setInterval creates interval #3
within 3 seconds interval #1 fires
within 3 seconds interval #2 fires
3 seconds later interval #3 fires
... intervals #1, #2 and #3 keep firing (three within 3 seconds)
So there's two problems. The interval keeps firing regardless of whether the system is still connected.
You might be better of just firing every 3 seconds with a single timer, and exiting if the connection is not available. This also allows using window.navigator.onLine, which has much better browser support.
I don't know how long you expect worksheet to be, but if you have the ApiService called through setTimeout 3 seconds apart, and then call the parent function every 3 seconds, you're going to be sending a lot of requests.
tryOffileWorkSheet: function () {
// (need to create `intervalId` in data)
if (this.intervalId) clearInterval(this.intervalId);
this.intervalId = setInterval(() => {
if (window.navigator.onLine) {
this.getWorkSheet();
}
}, 3000);
},
getWorkSheet: function () {
let worksheet = JSON.parse(localStorage.getItem("worksheet"));
if (worksheet == null) {
worksheet = [];
}
for (let i = 0; i <= worksheet.length; i++) {
if (worksheet.length > 0) {
setTimeout(() => {
if (worksheet[i]?.work_order_id) {
ApiService.get(
`/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
).then((response) => {
if (response.data.status) {
worksheet.splice(i, 1);
localStorage.setItem("worksheet", JSON.stringify(worksheet));
}
console.log("After", worksheet);
});
}
}, i * 300);
}
}
},
I am trying to get a current video progress value every 5 seconds so I can then make a post to the DB to store it againt User video progress table using JS and Plyr.js API but clearly doing something wrong. My code:
player.on('timeupdate', () => {
const currentTime = document.getElementById('current-time');
currentTime.innerText = player.currentTime;
let intervalId = setInterval( () => {
console.log(`Submitted timestamp to DB every 5 sec`)
}, 5000);
if (intervalId) {
clearInterval(intervalId);
}
//console.log(player.currentTime);
});
The code above does not fire console.log at all. If I remove clearInterval() the console.log gets fired after 5 sec but then repeats every second or so, not after 5 sec.
Found a solution after trawling the Plyr docs, listening to play is an option:
player.on('play', () => {
setInterval( function() {
// POST current time and state to the server
console.log(player.currentTime);
const currentTime = document.getElementById('current-time');
currentTime.innerText = player.currentTime;
}, 3000);
//console.log(player.currentTime);
});
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);
}
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
}