Store user video progress every 30 sec Plyr.js - javascript

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

Related

How to make a countdown timer for 5 second countdown?

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!

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 download data from axios in advance in vue?

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);
}
}
},

Double interval call and it should not be in node.js

I have problem on server side (node.js) with setInterval.
I want to check something every day at specific time and I set interval like this:
let maintainTime = backFunc.getNextMaintainTime(new Date());
let maintain = setInterval(() => {
let currentTime = new Date();
if (currentTime.getTime() > maintainTime.getTime()) {
maintainTime = backFunc.getNextMaintainTime(maintainTime);
//do the maintain
}
}, 360000);
//360000 to check on every hour
and here is my getNextMaintainTime function:
getNextMaintainTime: (maintainTime) => {
maintainTime.setDate(maintainTime.getDate() + 1);
maintainTime.setHours(4);
maintainTime.setMinutes(0);
maintainTime.setSeconds(0);
maintainTime.setMilliseconds(0);
return maintainTime;
}
When I test it out it works perfectly but when I start server on production every time it calls this function 2 times instead of 1 time at 4am, what could cause the problem?

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 :)

Categories