'How to handle an interval play pause stop in javascript or nodejs?
I have a main file that acts like an API to manage the playing, resuming or a video.
main.js
const { mainModule } = require('process');
const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js');
function init(payload) {
if(payload.type === 'play') {
handlePlayVideo(payload.data)
} else if(payload.type === 'pause') {
handlePauseVideo(payload.data);
} else if(payload.type === 'stop') {
handleStopVideo(payload.data);
}
}
function handlePlayVideo(data) {
startVideo(data).then(() => {
console.log('Video state: play');
});
}
function handlePauseVideo(data) {
pauseVideo().then(() => {
console.log('Video state: pause');
});
}
function handleStopVideo(data) {
stopVideo().then(() => {
console.log('Video state: stop');
});
}
I want to be able to use the data every second when the state(payload.type) is 'play'. That would start my interval, but I'm stuck on how to be able to pause it (then continue later from the same second), or stop it.
This is what I've tried:
video.js
module.exports = (function () {
let currentSecond = 0;
let videoIsPaused = false;
let videoIsStopped = false;
function startVideo(data) {
const videoTicker = setInterval(() => {
if(videoIsPaused || videoIsStopped) {
console.log('video is paused or stopped');
clearInterval(videoTicker);
if(videoIsStopped) currentSecond = 0;
}
parseVideo(data.someData, currentSecond);
if(currentSecond === 100) clearInterval(scenarioTicker);
currentSecond++;
}, 1000);
}
function pauseVideo() {
videoIsPaused = true;
}
function videoIsStopped() {
videoIsStopped = true;
}
function parseVideo(data) {
// do something (stream) the data every second, except when the video is paused, or stopped
}
})();
With this code, the startVideo method starts executing every second, but I cannot pause it.
Update: The starting of the video has been started(tested) using cli (ex. node main.js), which started the execution of start video for let's say one minute. In the same time, I'm opening a second cmd window, where I try to call the pauseVideo of the first window. So I think that my issue is because of the separate window environments which acts like a different scope, and I assume that my calls cannot interact with each other in this way. Is there a better way of doing/testing this?
Solution 1:[1]
In your if statement for the paused/stopped condition, you're not stopping the execution of the rest of the function. Therefore, the parts below it, like increasing currentSecond will still be hit. Perhaps an early return is what you need:
if(videoIsPaused || videoIsStopped) {
console.log('video is paused or stopped');
clearInterval(videoTicker);
if(videoIsStopped) currentSecond = 0;
return;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jacob |
