Timer doesn't start running - javascript

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?

I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}

you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/

In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

Related

How can I fix the stop-start process within this Javascript stopwatch-clock?

I have a JavaScript stopwatch here, I require the start-stop button to keep the same time when continuing.
Currently, if I stop and continue the clock diff is something ridiculous such as '-19330839:-3:-53'
Can anyone explain how this is fixed?
I have various method stopwatches made; however I would rather use real date time instead of a counter, this is because (I have tested after being made aware of this) that counters are very inaccurate over a period of time.
Any help is much appreciated.
html:
Please ignore the reset button for now. I will configure this later.
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();"/>
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
JS:
const outputElement = document.getElementById("outputt");
var startTime = 0;
var running = false;
var splitcounter = 0;
function startstop() {
if (running == false) {
running = true;
startTime = new Date(sessionStorage.getItem("time"))
if (isNaN(startTime)) startTime = Date.now();
startstopbutton.value = 'Stop';
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
updateTimer();
} else {
running = false;
logTime();
startstopbutton.value = 'Start';
document.getElementById("outputt").style.backgroundColor = "#B3321B";
}
}
function updateTimer() {
if (running == true) {
let differenceInMillis = Date.now() - startTime;
sessionStorage.setItem("time", differenceInMillis)
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
requestAnimationFrame(updateTimer);
}
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
I just need the timer to continue on from where it was stopped at.
Issue with your code:
You start with initial value for sessionStorage as Date.now but then save difference on update.
You interact a lot with session storage. Any communication with external API is expensive. Instead use local variables and find an event to initialise values.
Time difference logic is a bit off.
Date.now - startTime does not considers the difference between stop action and start action.
You can use this logic: If startTime is defined, calculate difference and add it to start time. If not, initialise it to Date.now()
Suggestions:
Instead of adding styles, use classes. That will help you in reset functionality
Define small features and based on it, define small functions. That would make reusability easy
Try to make functions independent by passing arguments and only rely on them. That way you'll reduce side-effect
Note: as SO does not allow access to Session Storage, I have removed all the related code.
const outputElement = document.getElementById("outputt");
var running = false;
var splitcounter = 0;
var lastTime = 0;
var startTime = 0;
function logTime() {
console.log('Time: ', lastTime)
}
function resetclock() {
running = false;
startTime = 0;
printTime(Date.now())
applyStyles(true)
}
function applyStyles(isReset) {
startstopbutton.value = running ? 'Stop' : 'Start';
document.getElementById("outputt").classList.remove('red', 'green')
if (!isReset) {
document.getElementById("outputt").classList.add(running ? 'red' : 'green')
}
}
function startstop() {
running = !running;
applyStyles();
if (running) {
if (startTime) {
const diff = Date.now() - lastTime;
startTime = startTime + diff;
} else {
startTime = Date.now()
}
updateTimer(startTime);
} else {
lastTime = Date.now()
logTime();
}
}
function printTime(startTime) {
let differenceInMillis = Date.now() - startTime;
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
}
function updateTimer(startTime) {
if (running == true) {
printTime(startTime)
requestAnimationFrame(() => updateTimer(startTime));
}
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
.red {
background-color: #2DB37B
}
.green {
background-color: #B3321B
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();" />
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
simple stopwatch example
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input class="startstop" style="width: 120px;" type="button" value="Start" onclick="startstop();">
<input class="reset" style="width: 120px;" type="button" value="Reset" onclick="reset();"/>
<div class="timerClock" value="00:00:00">00:00:00</div>
<script type="text/javascript">
var second = 0
var minute = 0
var hour = 0
var interval
var status = false
var element = document.querySelector('.startstop')
var clock = document.querySelector('.timerClock')
var string = ''
function startstop()
{
if(status == 'false')
{
element.value = 'Stop'
clock.style.backgroundColor = "#2DB37B";
status = true
interval = setInterval(function()
{
string = ''
second += 1
if(second >= 60)
{
minute += 1
second = 0
}
if(minute >= 60)
{
hour += 1
minute = 0
}
if(hour < 10)
string += `0${hour}:`
else
string += `${hour}:`
if(minute < 10)
string += `0${minute}:`
else
string += `${minute}:`
if(second < 10)
string += `0${second}`
else
string += `${second}`
clock.innerHTML = string
},1000)
}
else
{
clock.style.backgroundColor = "#B3321B";
element.value = 'Start'
status = false
clearInterval(interval)
}
}
function reset()
{
second = 0
minute = 0
hour = 0
status = false
element.value = 'Start'
clearInterval(interval)
clock.innerHTML = `00:00:00`
clock.style.backgroundColor = "transparent";
}
</script>
</body>
</html>
One thing to know about requestAnimationFrame is that it returns an integer that is a reference to the next animation. You can use this to cancel the next waiting animation with cancelAnimationFrame.
As mentioned by #Rajesh, you shouldn't store the time each update, as it will stop the current process for a (very) short while. Better in that case to fire an event, preferably each second, that will wait until it can run. I haven't updated the code to take that into account, I only commented it away for now.
It's also better to use classes than updating element styles. I wrote sloppy code that overwrites all classes on the #outputt element (it's spelled "output"). That's bad programming, because it makes it impossible to add other classes, but it serves the purpose for now. #Rajesh code is better written for this purpose.
I added two variables - diffTime and animationId. The first one corrects startTime if the user pauses. The second one keeps track if there is an ongoing timer animation.
I refactored your style updates into a method of its own. You should check it out, because it defines standard values and then changes them with an if statement. It's less code than having to type document.getElementById("outputt").style... on different rows.
I also added a resetclock method.
const outputElement = document.getElementById("outputt");
var startTime = 0;
var diffTime = 0;
var animationId = 0;
function startstop() {
const PAUSED = 0;
let paused = animationId == PAUSED;
//diffTime = new Date(sessionStorage.getItem("time")) || 0;
startTime = Date.now() - diffTime;
if (paused) {
updateTimer();
} else {
cancelAnimationFrame(animationId);
animationId = PAUSED;
}
updateTimerClass(paused);
}
function updateTimerClass(paused) {
var outputClass = 'red';
var buttonText = 'Start';
if (paused) {
outputClass = 'green';
buttonText = 'Stop';
}
startstopbutton.value = buttonText;
outputElement.classList = outputClass;
}
function updateTimer() {
let differenceInMillis = Date.now() - startTime;
//sessionStorage.setItem("time", differenceInMillis)
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
diffTime = differenceInMillis;
animationId = requestAnimationFrame(updateTimer);
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
function resetclock() {
let paused = animationId == 0;
startTime = Date.now();
diffTime = 0;
if (paused) {
const REMOVE_ALL_CLASSES = '';
outputElement.className = REMOVE_ALL_CLASSES;
outputElement.innerText = '00:00:00';
}
}
#outputt.green {
background-color: #2DB37B;
}
#outputt.red {
background-color: #B3321B;
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();"/>
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
class Stopwatch {
constructor(display, results) {
this.running = false;
this.display = display;
this.results = results;
this.laps = [];
this.reset();
this.print(this.times);
}
reset() {
this.times = [ 0, 0, 0 ];
}
click(){
var x=document.getElementById('ctrl');
if(x.value=="start"){
this.start();
x.value="stop";
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
}
else{
x.value="start";
this.stop();
document.getElementById("outputt").style.backgroundColor = "#B3321B";
}
}
start() {
if (!this.time) this.time = performance.now();
if (!this.running) {
this.running = true;
requestAnimationFrame(this.step.bind(this));
}
}
stop() {
this.running = false;
this.time = null;
}
resets() {
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
if (!this.time) this.time = performance.now();
if (!this.running) {
this.running = true;
requestAnimationFrame(this.step.bind(this));
}
this.reset();
}
step(timestamp) {
if (!this.running) return;
this.calculate(timestamp);
this.time = timestamp;
this.print();
requestAnimationFrame(this.step.bind(this));
}
calculate(timestamp) {
var diff = timestamp - this.time;
// Hundredths of a second are 100 ms
this.times[2] += diff / 1000;
// Seconds are 100 hundredths of a second
if (this.times[2] >= 100) {
this.times[1] += 1;
this.times[2] -= 100;
}
// Minutes are 60 seconds
if (this.times[1] >= 60) {
this.times[0] += 1;
this.times[1] -= 60;
}
}
print() {
this.display.innerText = this.format(this.times);
}
format(times) {
return `\
${pad0(times[0], 2)}:\
${pad0(times[1], 2)}:\
${pad0(Math.floor(times[2]), 2)}`;
}
}
function pad0(value, count) {
var result = value.toString();
for (; result.length < count; --count)
result = '0' + result;
return result;
}
function clearChildren(node) {
while (node.lastChild)
node.removeChild(node.lastChild);
}
let stopwatch = new Stopwatch(
document.querySelector('.stopwatch'),
document.querySelector('.results'));
<input type="button" id="ctrl" value="start" onClick="stopwatch.click();">
<input type="button" value="Reset" onClick="stopwatch.resets();">
<div id="outputt" class="stopwatch"></div>

Pause/Continue in Pomodoro Timer project

I am building a pomodoro tracker in order to practice a little bit of JavaScript. It's been a while since I started this project. After this particulary problem which is implement a pause/continue functionality I abandoned the project. I really got stucked. I know programming is not easy and I will be facing many problems in the future but I really can't figure out how to solve this task. I am feeling stupid
Here is the JavaScript code:
// General Variables
let display = document.querySelector('.display');
// is the timer paused?
// let isPaused = true;
// let count = 0;
//const playPomodoro = document.querySelector('.play');
const pause = document.querySelector('.pause');
const resume = document.querySelector('.resume');
const stopPomodoro = document.querySelector('.stop');
const pomodoro = document.querySelector('#pomodoro');
const shortBreak = document.querySelector('#shortbreak');
const longBreak = document.querySelector('#longbreak')
const audioBeep = document.querySelector('#audioBeep');
const twentyFiveMinutes = 60 * 25;
const fiveMinutes = 60 * 5;
const thirtyMinutes = 60 * 30;
// Start Pomodoro timer 25 minutes
pomodoro.addEventListener('click', () => {
startTimer(twentyFiveMinutes, display);
stopClick(shortBreak, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro short break
shortBreak.addEventListener('click', () => {
startTimer(fiveMinutes, display);
stopClick(pomodoro, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro Long break
longBreak.addEventListener('click', () => {
startTimer(thirtyMinutes, display);
stopClick(pomodoro, shortBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Stopping Clicks Events
function stopClick(btn1, btn2) {
btn1.classList.add('avoid-clicks');
btn2.classList.add('avoid-clicks');
}
// Remove .avoid-clicks class
function removeAvoidClick(btn1, btn2, btn3) {
btn1.classList.remove('avoid-clicks');
btn2.classList.remove('avoid-clicks');
btn3.classList.remove('avoid-clicks');
}
// main start timer function
function startTimer(duration, display) {
let timer = duration, min, sec;
let countingDown = setInterval(function() {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
display.innerHTML = min + ":" + sec;
if (--timer < 0) {
timer = duration;
}
// stops the counting variable when it hits zero
if (timer == 0) {
clearInterval(countingDown);
display.innerHTML = "00:00";
audioBeep.play();
removeAvoidClick(pomodoro,shortBreak,longBreak);
}
// Pause the clock
pause.addEventListener('click', () => {
});
// Stop the counter and set it to 00:00 when the user clicks the stop button
stopPomodoro.addEventListener('click', () => {
clearInterval(countingDown);
display.innerHTML = "00:00";
removeAvoidClick(pomodoro,shortBreak,longBreak);
});
}, 1000);
}
I will store the timer status in an object, then you activate a timer that decreses the current time left and call UI update.
let timer = {
timeLeft: 0,
running: 0,
};
function startTimer(duration) {
timer.timeLeft = duration;
if (!timer.run) {
timer.run = true;
run();
}
}
function run() {
if (timer.run) {
timer.timeLeft -= 1;
setTimeout(run, 1000)
}
}
function pauseTimer() {
timer.run = false;
}
function resumeTimer() {
if (!timer.run) {
timer.run = true;
run();
}
update();
}
function update() {
// everything you need to update in the UI from the timer object
}

How to make a countdown with input field with how many minutes the countdown must go?

I have made a countdown but now I want to make a input field with how many minutes the countdown should countdown from. What I have is a pretty basic countdown but what I don't have is that a user puts the amount of minutes into the input field, click the button, and it counts down the minutes. And I hope someone can help me with this.
This is what I got so far:
(()=> {
let countdownEnded = false;
start(3600); // seconds
})();
function start(inputTime){
let startTime = Date.now();
intervalSeconds = setInterval(() => {
let currentTime = Date.now() - startTime;
if(inputTime < 1) {
stop();
} else {
updateDisplay(inputTime, currentTime);
updateMillis();
}
}, 1000);
}
function stop(){
let countDivElement = document.getElementById("countdown"); /*** Updated***/
countDivElement.innerHTML = 'countdown done';
countdownEnded = true; /*** Updated***/
}
function updateDisplay(seconds, currentTime){
let timeIncrement = Math.floor(currentTime / 1000);
updateTime(seconds - timeIncrement);
}
/**
* #method - updatesecondsond
* #summary - This updates the timer every seconds
*/
function updateTime(seconds) {
let countDivElement = document.getElementById("timer");
let minutes = Math.floor(seconds / 60);
let remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds > 0) {
seconds = seconds - 1;
} else {
clearInterval(intervalSeconds);
countdownEnded = true;
countDivElement.innerHTML = 'countdown done';
return null;
}
countDivElement.innerHTML = minutes + ":" + remainingSeconds + ":" ;
};
function updateMillis() {
let countMillsElement = document.getElementById('millis');
let counterMillis = 99;
let millis;
let intervalMillis = setInterval(()=> {
if(counterMillis === 1) {
counterMillis = 99;
} else {
millis = counterMillis < 10 ? '0' + counterMillis : counterMillis;
};
countMillsElement.innerHTML = millis;
counterMillis --;
}, 10);
if(countdownEnded) {
stop(); /*** Updated***/
return clearInterval(intervalMillis);
}
};
<div class="clock" id="model3">
<div id="countdown"> <!-- Updated -->
<span id="timer"></span><span id="millis"></span>
</div>
</div>
<input id="minutes" placeholder="0:00"/>
I think this may help you.
Change the following
<input id="minutes" placeholder="00"/> <button onclick="startTimer()">Start</button>
And in javascript add a new function
function startTimer(){
var x=document.getElementById("minutes").value * 60; //To Change into Seconds
start(x);
}
And remove the start function
Just add a button with click event that takes input value and triggers your 'start' function with that value as parameter. Something like this:
document.getElementById("startBtn").addEventListener("click", startTimer);
function startTimer() {
var numberOfMinutes = Number(document.getElementById("minutes").value) * 60;
start(numberOfMinutes);
}
And remove 'start' function call from the window load to prevent the timer to start immidiately.
Result is something like this:
https://jsfiddle.net/scarabs/6patc9mo/1/

JS function stopwatch application confuses the user

I wrote a javascript application but I end up with a total confusion. This js application needs to run in minutes, seconds, and hundredths of seconds. The part about this mess is when the stopwatch show, in this case 03:196:03. Here is my confusion. When the stopwatch shows 196, is it showing hundredth of seconds? Does anybody can check my function and tell me what part needs to be corrected in case that the function is wrong?
<html>
<head>
<title>my example</title>
<script type="text/javascript">
//Stopwatch
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
document.getElementById("countDown").disabled = true;
document.getElementById("resetCountDown").disabled = true;
document.getElementById("start").innerHTML = "Stop";
} else {
run = 0;
document.getElementById("start").innerHTML = "Resume";
}
}//End function startWatch
function watchReset() {
run = 0;
time = 0;
document.getElementById("start").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
document.getElementById("countDown").disabled = false;
document.getElementById("resetCountDown").disabled = false;
}//End function watchReset
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
var min = Math.floor(time/10/60);
var sec = Math.floor(time/10);
var tenth = time % 10;
if (min < 10) {
min = "0" + min;
}
if (sec <10) {
sec = "0" + sec;
} else if (sec>59) {
var sec;
}
document.getElementById("output").innerHTML = min + ":" + sec + ":0" + tenth;
timeIncrement();
},10);
}
} // end function timeIncrem
function formatNumber(n){
return n > 9 ? "" + n: "0" + n;
}
</script>
</head>
<body>
<h1>Stopwatch</h1>
<p id="output"></p>
<div id="controls">
<button type="button" id ="start" onclick="startWatch();">Start</button>
<button type="button" id ="reset" onclick="watchReset();">Reset</button>
</div>
</body>
</html>
Your code is totally weird!
First you're using document.getElementById() for non-existing elements: maybe they belong to your original code and your didn't posted it complete.
Then I don't understand your time-count method:
you make timeIncrement() to be launched every 10 ms: so time/10 gives you a number of milliseconds
but you compute min and sec as if it was a number of seconds!
From there, all is wrong...
Anyway IMO your could make all that simpler using the getMilliseconds() function of the Date object.
Try this:
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
} else {
run = 0;
}
}
function watchReset() {
run = 0;
time = 0;
document.getElementById("output").innerHTML = "00:00:00";
}
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
timeIncrement();
},10);
}
}
function formatNumber(n){
return (n < 10 ? "0" : "") + n;
}
startWatch()
<div id="output"></div>

Button onclick performing multiple actions

I have this code:
var hour = parseInt(js_arr[j].substring(0, 1));
var min = parseInt(js_arr[j].substring(3, 4));
var seconds = parseInt(js_arr[j].substring(6, 7));
var mil_sec = parseInt(js_arr[j].substring(9, 11));
var time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
function timeout() {
setTimeout(function () {
if (true) {
document.getElementById('subs').innerHTML = js_arr[i];
i = i + 4;
j = j + 4;
hour = parseInt(js_arr[j].substring(0, 1));
min = parseInt(js_arr[j].substring(3, 4));
seconds = parseInt(js_arr[j].substring(6, 7));
mil_sec = parseInt(js_arr[j].substring(9, 11));
time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
timeout();
} else {
timeout();
}
}, time);
}
Before javascript code I have an onclick="timeout(); button.
This button allows subtitles to play. What I would also like it to do is to stop these subtitles from playing by clicking on that same button. It would be great if someone could help!
Thanks a lot.
Add a variable that indicates whether the timeout is active. In the timeout()-function, this variable is checked and another loop is only initiated when it is true. To Start and Stop you simply set (and call timeout()) or reset the variable.
var hour = parseInt(js_arr[j].substring(0,1));
var min = parseInt(js_arr[j].substring(3,4));
var seconds = parseInt(js_arr[j].substring(6,7));
var mil_sec = parseInt(js_arr[j].substring(9,11));
var time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
var timeOutRunning = false;
function startTimeOut() {
timeOutRunning = true;
timeout();
}
function stopTimeOut() {
timeOutRunning = false;
}
function timeout() {
if(timeOutRunning) {
setTimeout(function() {
document.getElementById('subs').innerHTML = js_arr[i];
i=i+4;
j=j+4;
hour = parseInt(js_arr[j].substring(0,1));
min = parseInt(js_arr[j].substring(3,4));
seconds = parseInt(js_arr[j].substring(6,7));
mil_sec = parseInt(js_arr[j].substring(9,11));
time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
timeout();
}, time);
}
}
And then the onclick-function:
onclick="if(timeOutRunning) { stopTimeOut(); } else { startTimeOut(); }"

Categories