JavaScript show div and add class if countdown has ended - javascript

I have some JavaScript with a countdown ticker, when it reaches 0 it displays the text "ended".
When this happens I need to display block on two divs and add a class to another div.
Here is the JS code:
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (+new Date);
if ( msLeft < 1000 ) {
element.innerHTML = "Ended";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + 'h ' + twoDigits( mins ) : mins) + 'm ' + twoDigits( time.getUTCSeconds() + 's' );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
countdown( "countdown", 1, 5 );
countdown( "countdown2", 100, 0 );
HTML:
<div id="countdown"></div>
Here is a fiddle: https://jsfiddle.net/vek5808u/8/
Any help would be great
Thanks

inside the if block
if ( msLeft < 1000 ) {
document.querySelector(".messaging").style.display="block";
document.querySelector(".img-message").style.display="block";
document.querySelector(".img-container").className += " opacity-overlay";
element.innerHTML = "Ended";
}
https://jsfiddle.net/vek5808u/36/

There is a bit of delay between when the time starts and the time is displayed. You may need to play around with that, but the procedure is pretty simple.
I based the Countdown class on a Repeater class that someone created in another question.
I even wrapped it in a jQuery plugin for ease of use.
const twoDigits = n => n <= 9 ? '0' + n : n;
const dispTime = t => {
var h = t.getUTCHours(), m = t.getUTCMinutes();
return (h ? h + 'h ' + twoDigits(m) : m) + 'm ' + twoDigits(t.getUTCSeconds() + 's')
};
function Countdown(minutes, seconds, callbackFn, successFn, scope) {
var self = this;
this.delay = 1000;
this.timer = setTimeout(function() { self.run(); }, this.delay);
this.callbackFn = callbackFn;
this.successFn = successFn;
this.endTime = new Date().getTime() + 1000 * (60 * minutes + seconds);
this.scope = scope || self;
}
Countdown.prototype.run = function() {
var self = this, timeRemaining = this.timeRemaining();
this.callbackFn.call(this.scope, timeRemaining);
if (timeRemaining < this.delay - 1) {
this.successFn.call(this.scope);
} else {
this.timer = setTimeout(function() { self.run(); }, this.delay);
}
};
Countdown.prototype.timeRemaining = function() {
return this.endTime - new Date().getTime();
};
(function($) {
$.fn.countdown = function(minutes, seconds, callbackFn, successFn) {
new Countdown(minutes, seconds, callbackFn, successFn, this);
return this;
};
})(jQuery);
$('#countdown').countdown(0, 10, function(msRemaining) {
this.html(dispTime(new Date(msRemaining)));
}, function() {
this.html("Ended");
$('.img-message').show();
});
.messaging,
.img-message {
display: none;
}
.img-container.opacity-overlay {
opacity: 0.6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<div class="messaging">
<p>messaging here</p>
</div>
<div class="img-container">
<div class="img-message">image message here</div>
</div>

Related

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/

How to make HH:MM:SS countdown timer, using javascript?

i've tried to make simple countdown timer, but i don't know how to make something when the timer ends and i don't know how to make timer with hours HH. I can make only minutes MM and second SS.
So, i have this HTML code:
<div class="tadc-time-display">
<span class="tadc-time-display-hours_minutes">00:00</span>
<span class="tadc-time-display-seconds">00</span>
</div>
The JS code i used to have is useless(
You can use Native JavaScript or jQuery, if you want)
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 0.1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
It should also start, stop and reset, but i dont know how to do it( Thanks a lot!
var hours = 0, // obtain these values somewhere else
minutes = 1,
seconds = 20,
target = new Date(),
timerDiv = document.getElementById("timer"),
handler;
function init() {
// set the target date time with the counter values
// counters more then 24h should have a date setup or it wont work
target.setHours(hours);
target.setMinutes(minutes);
target.setSeconds(seconds);
target.setMilliseconds(0); // make sure that miliseconds is 0
timerDiv.innerHTML = target.toTimeString().split(" ")[0]; // print the value
}
function updateTimer() {
var time = target.getTime();
target.setTime(time - 1000); // subtract 1 second with every thick
timerDiv.innerHTML = target.toTimeString().split(" ")[0];
if (
target.getHours() === 0 &&
target.getMinutes() === 0 &&
target.getSeconds() === 0
) { // counter should stop
clearInterval(handler);
}
}
handler = setInterval(updateTimer, 1000);
document.getElementById("stop-button").addEventListener("click", function() {
clearInterval(handler);
});
document.getElementById("start-button").addEventListener("click", function() {
clearInterval(handler);
handler = setInterval(updateTimer, 1000);
});
document.getElementById("reset-button").addEventListener("click", function() {
init();
clearInterval(handler);
});
init();
<div id="timer"></div>
<div>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<button id="reset-button">Reset</button>
</div>
Here is working sample with comments.
try this :
<html lang="en"><head>
<style>
#import "//fonts.googleapis.com/css?family=Bangers";
body {
margin: 0;
}
.wrap {
display: flex;
align-items: center;
justify-content: center;
background:#111;
}
.time-to {
text-align: center;
font-family: Bangers;
color: white;
font-size: 50px;
}
.underline {
text-decoration: underline;
}
.time-to span {
display: block;
font-size: 70px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div class="wrap ng-scope" ng-app="app">
<div class="time-to">
prochain event dans :
<span countdown="" date="november 17, 2019 15:15:50" class="ng-isolate-scope underline"></span>
<br>
event : minecraft , ip: 144.76.116.78:40020
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script id="rendered-js">
(function () {
angular.module('app', []).directive('countdown', [
'Util',
'$interval',
function (Util,
$interval) {
return {
restrict: 'A',
scope: {
date: '#' },
link: function (scope,
element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
return element.text(Util.dhms(diff));
},
1000);
} };
}]).
factory('Util', [
function () {
return {
dhms: function (t) {
var days,
hours,
minutes,
seconds;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
return [days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'].join(' ');
} };
}]);
}).call(this);
</script>
</body></html>

Call a function when my timer reaches zero

I've got a timer function as follows (which I've just grabbed off a jsfiddle):
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function returnDate(){
return Number(new Date);
}
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (returnDate());
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
I call the function and set it to countdown to 2 minutes like so:
$(".btn-start").click(function(){
countdown("countdown-2-minutes",2,0);
});
I have another element with id countdown-8-minutes that I want to start immediately when the timer on countdown-2-minutes reaches 0. How should I do this? I suppose an okay way would be to monitor when the html on the first element reads "0:00" but I don't exactly know how to implement that.
Here's what I would suggest; First change your countdown() function to accept a callback parameter:
function countdown( elementName, minutes, seconds, callback )
{
var element, endTime, hours, mins, msLeft, time;
function returnDate(){
return Number(new Date);
}
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (returnDate());
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
if (typeof callback === 'function') {
callback.call()
}
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
then pass that callback with your initial call:
$(".btn-start").click(function(){
countdown("countdown-2-minutes",2,0, function(){countdown("countdown-8-minutes",8,0);});
});
Just call countdown() with the proper parameters when you detect that the timer is finished. Try this:
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
countdown("countdown-8-minutes",8,0);
}
You don't need to watch the element's content to know when to start the next timer. In fact you're already reacting to that happening on the line you check if ( msLeft < 1000 ) { in which you can start your next timer.
Once your current timer hits zero you can just start the next one inside that if statement.
Alternatively you can separate your timer logic from your element logic using something like this:
// CountdownTimer object. Give it a length (ms) to count to, a period (ms)
// to loop updates to the callback, and a callback (function(done:bool)) that
// handles update ticks where done=false and the final tick where done=true.
function CountdownTimer(length, period, callback) {
this.length = length;
this.period = period;
this.callback = callback;
// Assert the callback to be a function to avoid messy error handling, and
// show we noticed in the console.
if (typeof this.callback !== 'function') {
console.warn('Callback was not a function.');
this.callback = function(){};
}
// Some publically visible variables for time keeping.
this.startTime = 0;
this.elapsed = 0;
this.remaining = length;
// The _loop scope's 'this' is itself. Give it a handle on the CountdownTimer's
// 'this' so we can reference the variables inside the loop.
var scope = this;
// Main loop of the countdown timer.
this._loop = function() {
// Get the number of milliseconds since the countdown started.
scope.elapsed = Date.now() - scope.startTime;
if (scope.elapsed < scope.length) {
// Keep looping if the countdown is not yet finished.
scope.remaining = scope.length - scope.elapsed;
scope.callback(false);
} else {
// Finished looping when the countdown hits or passes the target.
scope.elapsed = scope.length;
scope.remaining = 0;
scope.callback(true);
// Stop the interval timer from looping again.
clearInterval(scope._t);
}
};
}
// This function starts up the CountdownTimer
CountdownTimer.prototype.start = function() {
this.startTime = Date.now();
this._t = setInterval(this._loop, this.period);
}
// Our test elements.
var progress2 = document.getElementById('prog-2m');
var progress8 = document.getElementById('prog-8m');
var clockElement = document.getElementById('clock');
var startButton = document.getElementById('start');
// The 2-minute timer.
var m2 = new CountdownTimer(2 * 60 * 1000, 33, function(done) {
// Calculate the time to display.
var mins = Math.floor(m2.remaining / 60 / 1000);
var secs = Math.floor(m2.remaining / 1000) % 60;
if (secs < 10) secs = '0' + secs;
clockElement.textContent = mins + ':' + secs;
if (done) {
// If we're done, set the timer to show zero and start the next timer.
clockElement.textContent = '0:00';
m8.start();
}
// Progress bar display update.
progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';
});
// The 8-minute timer.
var m8 = new CountdownTimer(8 * 60 * 1000, 33, function(done) {
// Calculate the time to display.
var mins = Math.floor(m8.remaining / 60 / 1000);
var secs = Math.floor(m8.remaining / 1000) % 60;
if (secs < 10) secs = '0' + secs;
clockElement.textContent = mins + ':' + secs;
if (done) {
// Once done, set the timer to zero and display "Done".
clockElement.textContent = '0:00 Done';
}
// Progress bar display update.
progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';
});
// Start the 2-minute timer when the button is clicked.
startButton.addEventListener('click', function() {
m2.start();
});
#progress {
width: 200px;
height: 20px;
border: 2px solid #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
border-radius: 2px;
position: relative;
margin: 8px 0;
}
#prog-2m {
width: 40px;
height: 20px;
background-color: #3c9;
position: absolute;
left: 0;
top: 0;
}
#prog-8m {
width: 160px;
height: 20px;
background-color: #c33;
position: absolute;
left: 40px;
top: 0;
}
<div id="progress">
<div id="prog-2m"></div>
<div id="prog-8m"></div>
</div>
<div id="clock">0:00</div>
<button id="start">Begin</button>

Jquery timer countdown and countup

I am trying to track down the time for a basketball game.
What I need is
A countdown timer with pause and continue.
For that i use the code found at
http://jchavannes.com/jquery-timer/demo
I also need to track the time every player has been in the game. Not all the players are in the game simultaneously.
Problems that i want to solve.
1) Being able to start the countdown timer dynamically from any time. I mean when the page starts the time could be different each time.
2) Being able to add or substract minutes or seconds to the timer when it is stopped.
3) Being able to count up the time of the players that are in the game. That is when they are substituted their counting time should be paused and start counting the time of the players that got in the game.
4) As you can see I create a
var CustomPlayer1 = new (function() { ... }
var CustomPlayer2 = new (function() { ... }
I know it is not the best to create all this for all the players (possibly 24 for the two teams). How can this be created more efficiently?
That for the start. Anything else that may be needed for you to understand and possibly help me do this I will be glad to tell you.
What I have so far is the following. (it is far away for what i need)
<span id="stopwatchplayer1">00:10:00</span>
<br/>
<br/>
<span id="stopwatchplayer2">00:10:00</span>
<br/>
<br/
<h3>Example 2 - Countdown Timer</h3>
<span id="countdown">10:00:00</span>
<form id="example2form">
<input type='button' value='Play/Pause' onclick='Example2.Timer.toggle(), CustomPlayer1.Timer.toggle(), CustomPlayer2.Timer.toggle();' />
<input type='button' value='Stop/Reset' onclick='Example2.resetCountdown();' />
<input type='text' name='startTime' value='300' style='width:30px;' />
</form>
<script>
var CustomPlayer1 = new (function() {
// Stopwatch element on the page
var $stopwatchplayer1;
// Timer speed in milliseconds
var incrementTime = 150;
// Current timer position in milliseconds
var currentTime = 0;
// Start the timer
$(function() {
$stopwatchplayer1 = $('#stopwatchplayer1');
CustomPlayer1.Timer = $.timer(updateTimer, incrementTime, true);
});
// Output time and increment
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatchplayer1.html(timeString);
currentTime += incrementTime;
}
// Reset timer
this.resetstopwatchplayer1 = function() {
currentTime = 0;
CustomPlayer1.Timer.stop().once();
};
});
var CustomPlayer2 = new (function() {
// Stopwatch element on the page
var $stopwatchplayer2;
// Timer speed in milliseconds
var incrementTime = 150;
// Current timer position in milliseconds
var currentTime = 0;
// Start the timer
$(function() {
$stopwatchplayer2 = $('#stopwatchplayer2');
CustomPlayer2.Timer = $.timer(updateTimer, incrementTime, true);
});
// Output time and increment
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatchplayer2.html(timeString);
currentTime += incrementTime;
}
// Reset timer
this.resetstopwatchplayer2 = function() {
currentTime = 0;
CustomPlayer2.Timer.stop().once();
};
});
/**
* Example 2 is similar to example 1. The biggest difference
* besides counting up is the ability to reset the timer to a
* specific time. To do this, there is an input text field
* in a form.
*/
var Example2 = new (function() {
var $countdown,
$form, // Form used to change the countdown time
incrementTime = 70,
currentTime = 180000,
updateTimer = function() {
$countdown.html(formatTime(currentTime));
if (currentTime == 0) {
Example2.Timer.stop();
timerComplete();
Example2.resetCountdown();
return;
}
currentTime -= incrementTime / 10;
if (currentTime < 0) currentTime = 0;
},
timerComplete = function() {
//alert('Example 2: Countdown timer complete!');
console.log('Example 2: Countdown timer complete!');
},
init = function() {
$countdown = $('#countdown');
Example2.Timer = $.timer(updateTimer, incrementTime, true);
$form = $('#example2form');
$form.bind('submit', function() {
Example2.resetCountdown();
return false;
});
};
this.resetCountdown = function() {
var newTime = parseInt($form.find('input[type=text]').val()) * 100;
if (newTime > 0) {currentTime = newTime;}
this.Timer.stop().once();
};
$(init);
});
// Common functions
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
<script>
This is the answer i came up with, for anyone interested.
I used the jquery-runner as kasynych suggested yesterday.
github.com/jylauril/jquery-runner.
The answer can be found at http://jsfiddle.net/stefslam/mvx3jooz/7/
STYLE
.in_out {
width: 50px !important;
}
.cls_runner_in {
color: green;
}
.cls_runner_out {
color: red;
}
input[disabled=disabled], input:disabled {
cursor: default;
pointer-events: none;
/*Button disabled - CSS color class*/
color: #c0c0c0 !important;
background-color: #ffffff !important;
}
HTML
<div id="container">
<span id="runner" data-state="1" data-start="600000"></span>
<br />
<br />
<input type='button' id="StartStopButton" value='Play' />
<input type='button' class="edit_runner" data-type="min" data-value="1" data-disable="60000" id="PlusMin" value='+1 Min' />
<input type='button' class="edit_runner" data-type="min" data-value="-1" data-disable="60000" id="MinusMin" value='-1 Min' />
<input type='button' class="edit_runner" data-type="sec" data-value="1" data-disable="1000" id="PlusSec" value='+1 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="-1" data-disable="1000" id="MinusSec" value='-1 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="10" data-disable="1000" id="PlusSecs" value='+10 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="-10" data-disable="1000" id="MinusSecs" value='-10 Sec' />
<br />
<br />Player 1 : <span id="runner1" class="cls_runner cls_runner_in" data-ingame="1" data-start="120000">00:00</span>
<input type='button' class="in_out" data-tospanid="1" value='In' />
<br />
<br />Player 2 : <span id="runner2" class="cls_runner cls_runner_in" data-ingame="1" data-start="221000">00:00</span>
<input type='button' class="in_out" data-tospanid="2" value='In' />
<br />
<br />Player 3 : <span id="runner3" class="cls_runner cls_runner_in" data-ingame="1" data-start="0">00:00</span>
<input type='button' class="in_out" data-tospanid="3" value='In' />
<br />
<br />Player 4 : <span id="runner4" class="cls_runner cls_runner_out" data-ingame="2" data-start="1244">00:00</span>
<input type='button' class="in_out" data-tospanid="4" value='Out' />
<br />
<br />Player 5 : <span id="runner5" class="cls_runner cls_runner_in" data-ingame="1" data-start="10000">00:00</span>
<input type='button' class="in_out" data-tospanid="5" value='In' />
<br />
<br />Player 6 : <span id="runner6" class="cls_runner cls_runner_out" data-ingame="2" data-start="101022">00:00</span>
<input type='button' class="in_out" data-tospanid="6" value='Out' />
<br />
<br />
</div>
JAVASCRIPT
function Custom_millisecondsToString(milliseconds) {
var oneHour = 3600000;
var oneMinute = 60000;
var oneSecond = 1000;
var seconds = 0;
var minutes = 0;
var hours = 0;
var result;
if (milliseconds >= oneHour) {
hours = Math.floor(milliseconds / oneHour);
}
milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
if (milliseconds >= oneMinute) {
minutes = Math.floor(milliseconds / oneMinute);
}
milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
if (milliseconds >= oneSecond) {
seconds = Math.floor(milliseconds / oneSecond);
}
milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
if (hours > 0) {
result = (hours > 9 ? hours : "0" + hours) + ":";
} else {
result = "00:";
result = "";
}
if (minutes > 0) {
result += (minutes > 9 ? minutes : "0" + minutes) + ":";
} else {
result += "00:";
}
if (seconds > 0) {
result += (seconds > 9 ? seconds : "0" + seconds);
} else {
result += "00";
}
//alert (result);
return result;
}
$('.edit_runner').each(function () {
$(this).prop('disabled', true);
});
function checkToDisableButtons() {
var startstop_state = $('#runner').attr('data-state');
//console.log($('#runner').attr('data-state'));
//$('#runner').each(function() { alert($('#runner').attr('data-state')); });
console.log(startstop_state);
$('.edit_runner').each(function () {
$(this).prop('disabled', true);
});
if (startstop_state == 1) {
var runner_start = $('#runner').data('start');
var runner_value = $('#runner').html();
var piece_value = runner_value.split(':');
var current_value_millisecond = (parseFloat(piece_value[0]) * 60 + parseFloat(piece_value[1])) * 1000;
//$('.edit_runner').prop('disabled', true);
console.log('runner_start-current_value_millisecond<60000 = ' + runner_start + '-' + current_value_millisecond + '<' + 60000 + ' = ' + (runner_start - current_value_millisecond));
if (runner_start - current_value_millisecond > 60000) {
//$('.edit_runner[data-type="min"][data-value="1"]').prop('disabled', false);
$('#PlusMin').prop('disabled', false);
//console.log('PlusMin');
}
if (current_value_millisecond > 60000) {
$('#MinusMin').prop('disabled', false);
}
if (runner_start - current_value_millisecond > 1000) {
$('#PlusSec').prop('disabled', false);
}
if (current_value_millisecond > 1000) {
$('#MinusSec').prop('disabled', false);
}
if (runner_start - current_value_millisecond > 10 * 1000) {
$('#PlusSecs').prop('disabled', false);
}
if (current_value_millisecond > 10 * 1000) {
$('#MinusSecs').prop('disabled', false);
}
//alert (current_value_millisecond);
}
}
$("div#container").on('click', '.in_out', function () {
var temp_id;
var temp_action;
temp_id = $(this).data('tospanid');
temp_val = $(this).val();
//alert($(this).data('action')+' - '+$(this).val());
if (temp_val == 'In') {
$('#runner' + temp_id).css("color", "red").removeClass('cls_runner_in').addClass('cls_runner_out');
$(this).val('Out');
$(this).attr('data-action', 2);
} else {
$('#runner' + temp_id).css("color", "green").removeClass('cls_runner_out').addClass('cls_runner_in');
$(this).val('In');
$(this).attr('data-action', 1);
}
});
$('#runner').each(function () {
var $this = $(this);
$this.runner({
countdown: true,
milliseconds: false,
startAt: $this.data('start'), // alternatively you could just write: 10*60*1000 = 10 minutes data-start="10*60*1000"
stopAt: 0, // 2(min) * 60(sec) * 1000(ms) = 120000
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
}).on('runnerFinish', function (eventObject, info) {
$('.cls_runner_in, .cls_runner_out').each(function () {
$(this).runner('stop');
});
});
});
$('.cls_runner').each(function () {
var $this = $(this);
//console.log($this.data('start'));
$this.runner({
milliseconds: false,
startAt: $this.data('start'), // $(this).data('start')
//stopAt: $('#runner').data('start')
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
//$('.cls_runner_in').runner('toggle');
//$('.cls_runner_out').runner('stop');
$("div#container").on('click', '#StartStopButton', function () {
$('#runner').runner('toggle');
$(this).val($(this).val() == 'Play' ? 'Pause' : 'Play');
$(this).attr('data-state', $(this).attr('data-state') == '1' ? '2' : '1');
$('#runner').attr('data-state', $(this).attr('data-state') == '1' ? '2' : '1');
//console.log($(this).data('state'));
checkToDisableButtons();
$('.cls_runner_in').each(function () {
var $this = $(this);
//console.log($this.data('start'));
$this.runner('toggle');
});
//$('.cls_runner_out').runner('stop');
});
$("div#container").on('click', '.edit_runner', function () {
var current_type;
var current_value;
//$("#my_time").val($('.runner').runner('getCurrentTime'));
current_time = $('#runner').html();
current_type = $(this).data('type');
current_value = $(this).data('value');
current_cls_value = $(this).data('value') * (-1);
//alert (current_type+' - '+current_value);
var piece = current_time.split(':');
var current_millisecond = (parseFloat(piece[0]) * 60 + parseFloat(piece[1])) * 1000;
//alert (piece[0]+'*'+60+' + '+piece[1]);
//alert (current_millisecond);
if (current_type == 'min') {
var new_runner_time = current_millisecond + current_value * 60000;
$('.cls_runner_in').each(function () {
var $this = $(this);
current_cls_time = $this.html();
//console.log($this.data('start'));
var piece_cls = current_cls_time.split(':');
var current_cls_millisecond = (parseFloat(piece_cls[0]) * 60 + parseFloat(piece_cls[1])) * 1000;
var new_cls_time = current_cls_millisecond + current_cls_value * 60000;
$this.runner({
milliseconds: false,
startAt: new_cls_time,
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
} else {
var new_runner_time = current_millisecond + current_value * 1000;
$('.cls_runner_in').each(function () {
var $this = $(this);
current_cls_time = $this.html();
//console.log($this.data('start'));
var piece_cls = current_cls_time.split(':');
var current_cls_millisecond = (parseFloat(piece_cls[0]) * 60 + parseFloat(piece_cls[1])) * 1000;
var new_cls_time = current_cls_millisecond + current_cls_value * 1000;
$this.runner({
milliseconds: false,
startAt: new_cls_time,
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
}
//alert (mins);
$('#runner').runner({
countdown: true,
milliseconds: false,
startAt: new_runner_time, // alternatively you could just write: 10*60*1000 = 10 minutes data-start="10*60*1000"
stopAt: 0, // 2(min) * 60(sec) * 1000(ms) = 120000
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
checkToDisableButtons();
});

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