I use the following link codes, it works well, but I want the button to be clicked only once when the time is zero?
Enabling Button after certain time frame in Jquery html?
I changed the code as follows but it did not work?
function enableButton() {
var timer2 = "00:05";
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
if (minutes == 0 && seconds == 0) {
clearInterval(interval);
document.getElementById('Send_Active').addEventListener('click', function() {
enableButton();
alert('ok');
});
} else {
//document.getElementById('Send_Active').setAttribute('hidden', true);
}
}, 1000);
}
enableButton();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div id="countdown" class="countdown"></div>
</div>
<div class="form-group">
<a id="Send_Active">send again</a>
</div>
You can use removeEventListener() to remove the listener you added.
const btnSendActive = document.getElementById('Send_Active');
function buttonClicked() {
btnSendActive.removeEventListener('click', buttonClicked);
enableButton();
alert('ok');
}
function enableButton() {
var timer2 = "00:03";
var interval = setInterval(function() {
var timer = timer2.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
if (minutes == 0 && seconds == 0) {
clearInterval(interval);
btnSendActive.addEventListener('click', buttonClicked);
}
}, 1000);
}
enableButton();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div id="countdown" class="countdown"></div>
</div>
<div class="form-group">
<a id="Send_Active">send again</a>
</div>
Related
I have count-up timer and it reset every time after refreshing page or closing tab how can I can continue timer after refreshing or closing page so that after that i can insert that time in database.
I want to also set setInterval for after serval time to update time and store that time .
here is html code :
var h1 = document.getElementById("displaytime"),
start = document.getElementById("start"),
reset = document.getElementById("reset"),
pause = document.getElementById("pause"),
reset_timer = document.getElementById("displaytime"),
seconds = 0,
minutes = 0,
hours = 0,
count = 0,
t = -1;
function timer() {
t = setTimeout(add, 1000);
}
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent =
(hours ? (hours > 9 ? hours : "0" + hours) : "00") +
":" +
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" +
(seconds > 9 ? seconds : "0" + seconds);
timer();
}
function display_timer() {
count++;
console.log(displaytime);
}
setInterval(display_timer ,5000);
start.addEventListener("click", function() {
seconds = 0; minutes = 0; hours = 0;
clearInterval(t);
timer();
});
reset.addEventListener("click", function() {
clearTimeout(t);
reset_timer.innerHTML = '00:00:00';
pause.innerHTML = 'Pause';
});
pause.addEventListener('click', function(e) {
if (t == -1) {
pause.innerHTML = 'Pause';
timer();
} else {
pause.innerHTML = "Resume";
clearInterval(t);
t = -1;
}
});
<html>
<head>
<title>Timer</title>
</head>
<body>
<div class="Timer">
<section id="stopWatch">
<h1 id="displaytime">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset" >Reset</button>
</section>
</div>
</body>
</html>
I have made a stopwatch in javascript which accepts start time from get parameters. Everything is working but I would like to play a sound 3 seconds before end. SO far I have this:
HTML:
<form action="timer.php" method="get">
<select name="hours">
<?php for($i = 0; $i <= 24; $i++): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<select name="minutes">
<?php for($i = 0; $i <= 59; $i++): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<select name="seconds">
<?php for($i = 0; $i <= 59; $i++): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<input type="submit" name="submit" value="submit">
</form>
<div class="stopwatch">
Start stopwatch<br>
Stop stopwatch<br>
<span class="hours"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</div>
Javasciprt:
// GetParams class to parse $_GET[]
var GetParams = {
getSearchParameters: function() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? this.transformToAssocArray(prmstr) : {};
},
transformToAssocArray: function( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
};
var stopWatch = {
TimerID : null,
startHours : parseInt(GetParams.getSearchParameters().hours),
startMinutes : parseInt(GetParams.getSearchParameters().minutes),
startSeconds : parseInt(GetParams.getSearchParameters().seconds),
totalSeconds : parseInt(GetParams.getSearchParameters().seconds) + parseInt(GetParams.getSearchParameters().minutes) * 60 + parseInt(GetParams.getSearchParameters().hours) * 3600,
changeTimer: function () {
this.TimerID = setInterval(() => this.timerTick(), 1000);
$('.start-stopwatch').hide();
},
timerTick: function ()
{
this.totalSeconds--;
var hours = Math.floor(this.totalSeconds / 3600);
var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
if (this.totalSeconds === 0)
{
clearInterval(this.TimerID);
new Audio("/sources/sounds/interval.mp3").play();
}
},
isActive: function () {
return (this.totalSeconds > 0);
},
prePopulate: function () {
var hours = this.startHours;
var minutes = this.startMinutes;
var seconds = this.startSeconds;
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
},
stopTimer: function () {
$('.start-stopwatch').show();
clearInterval(this.TimerID);
}
};
With this code I am getting :
Unhandled Promise Rejection: NotAllowedError (DOM Exception 35): The
request is not allowed by the user agent or the platform in the
current context, possibly because the user denied permission.
I was reading and found out that sounds must be associated with user interaction such as click. User has to click on Start Stopwatch first and then the countdown starts.
I also found this: https://www.sitepoint.com/community/t/count-down-and-make-sound-play-on-click/30270/2
But dont know how should I implement it in my code.
I know that you can automatically click something using the click() function.
So say you have an html
<button id="mybtn"></button>
You can click that w/ JS by doing this:
var mybtn = document.getElementById('mybtn');
mybtn.click();
Hopefully that helps!!
Check out the function playAudio()
$(document).ready(function() {
var stopWatch = {
TimerID: null,
startHours: 0,
startMinutes: 0,
startSeconds: 3,
totalSeconds: 5,
changeTimer: function() {
this.TimerID = setInterval(() => this.timerTick(), 1000);
$('.start-stopwatch').hide();
},
timerTick: function() {
this.totalSeconds--;
var hours = Math.floor(this.totalSeconds / 3600);
var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
//I PUT 3 FOR TESTING PURPOSE
if (this.totalSeconds === 3) {
clearInterval(this.TimerID);
this.playAudio();
}
},
playAudio: function () {
//here you can set START,STOP,FILE
var startSecond = 20,
stopSecond = 30,
src ="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" ;
/* you can use createElement() if you need to append
a new tag audio at runtime
var audioElement = document.createElement('audio'); */
var audioElement = document.querySelector('audio');
audioElement.setAttribute('src', src + '#t=' + startSecond+','+stopSecond);
audioElement.play();
},
isActive: function() {
return (this.totalSeconds > 0);
},
prePopulate: function() {
var hours = this.startHours;
var minutes = this.startMinutes;
var seconds = this.startSeconds;
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
},
stopTimer: function() {
$('.start-stopwatch').show();
clearInterval(this.TimerID);
}
};
$(".start-stopwatch").click(()=> stopWatch.changeTimer());
$(".stop-stopwatch").click(()=> stopWatch.stopTimer());
//uncomment if you want to play on load of the page
//stopWatch.playAudio();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form action="timer.php" method="get">
........
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>
</form>
<div class="stopwatch">
Start stopwatch <br>
Stop stopwatch<br>
<span class="hours"></span>:
<span class="minutes"></span>:
<span class="seconds"></span>
</div>
I got it working :)
var stopWatch = {
TimerID : null,
startHours : parseInt(GetParams.getSearchParameters().hours),
startMinutes : parseInt(GetParams.getSearchParameters().minutes),
startSeconds : parseInt(GetParams.getSearchParameters().seconds),
totalSeconds : parseInt(GetParams.getSearchParameters().seconds) + parseInt(GetParams.getSearchParameters().minutes) * 60 + parseInt(GetParams.getSearchParameters().hours) * 3600,
sound : new Audio("/sources/sounds/interval.mp3"),
changeTimer: function () {
this.sound.play();
this.sound.pause();
this.TimerID = setInterval(() => this.timerTick(), 1000);
$('.start-stopwatch').hide();
},
timerTick: function ()
{
this.totalSeconds--;
var hours = Math.floor(this.totalSeconds / 3600);
var minutes = Math.floor(this.totalSeconds / 60) - (hours * 60);
var seconds = this.totalSeconds - (minutes * 60) - (hours * 3600);
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
if (this.totalSeconds === 0)
{
this.sound.play();
clearInterval(this.TimerID);
}
},
isActive: function () {
return (this.totalSeconds > 0);
},
prePopulate: function () {
var hours = this.startHours;
var minutes = this.startMinutes;
var seconds = this.startSeconds;
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.stopwatch .hours').text(hours);
$('.stopwatch .minutes').text(minutes);
$('.stopwatch .seconds').text(seconds);
},
stopTimer: function () {
$('.start-stopwatch').show();
clearInterval(this.TimerID);
}
};
I've been going about this for a while. Whenever I click "start" more than once, it adds up. If you notice, if I click "start" twice, the counting on my clock starts to act funny :
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0,
minutes = 0,
GG;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent =
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
timer();
start.onclick = timer;
stop.onclick = function() {
clearTimeout(GG);
}
clear.onclick = function() {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
</html>
I have to press STOP , N times as many as START.
If I want to fix this, to make any succeeding presses to START will not matter. Only one counting execution will be running at any time.
Add a variable to check click on start
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
<script>
var h1 = document.getElementsByTagName('h1')[0]
, start = document.getElementById('start')
, stop = document.getElementById('stop')
, clear = document.getElementById('clear')
, seconds = 0
, minutes = 0
, GG
, flag = true;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
start.onclick = function () {
if(flag)
{
timer();
flag = false;
}
}
stop.onclick = function () {
clearTimeout(GG);
flag = true;
}
clear.onclick = function () {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}
</script>
</html>
Below is my code in C# MVC 5. I have made a partial view called _ClockPartial.cshtml that is a simple stopwatch that i am putting into the main page Index.cshtml using "#Html.Partial("_ClockPartial")".
My question is how do i separate the javascript into the scripts folder (~/Scripts/clocker.js) but still have it function properly? When i tried to separate it myself, i haven't gotten it to properly work yet. I have heard you can't do this in partial views but i'm not sure why. Even if i can't do it in partial i would still like to know how to separate the javascript into its own file and call it in one of my .cshtml views. Thanks for your help in advance!
First file is my Index.cshtml
#{
ViewBag.Title = "Home Page";
}
#using Microsoft.AspNet.Identity
#Scripts.Render("~/bundles/jquery")
<div class="jumbotron">
<h1>Clocker</h1>
<p class="lead">Welcome to clocker! Please sign in to start clocking your hours! Don't do too little or your hard earned cash goes into the punishiment piggy bank!</p>
#if (Request.IsAuthenticated)
{
#Html.Partial("_ClockPartial")
}
<p>Learn more ยป</p>
</div>
And this is _ClockPartial.cshtml
#Scripts.Render("~/bundles/jquery")
<h2><time>03:00:00</time></h2>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<script type="text/javascript">
$(document).ready(function () {
var h1 = document.getElementsByTagName('h2')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 3,
isRunning = false,
t;
/* increments timer */
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
/* decrements timer */
function subtract() {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(subtract, 1000);
}
/* enable following line to start timer automatically */
//timer();
/* Start button */
start.onclick = function () {
if (!isRunning) {
timer();
isRunning = true;
}
}
/* Stop button */
stop.onclick = function () {
clearTimeout(t);
isRunning = false;
}
/* Clear button */
clear.onclick = function () {
h1.textContent = "03:00:00";
seconds = 0; minutes = 0; hours = 3;
isRunning = false;
}
});
</script>
<p></p>
Create a new js file in the Scripts folder and add the following code of your partial view in it, let's say it's name is clocker.js:
$(document).ready(function () {
var h1 = document.getElementsByTagName('h2')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 3,
isRunning = false,
t;
/* increments timer */
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
/* decrements timer */
function subtract() {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(subtract, 1000);
}
/* enable following line to start timer automatically */
//timer();
/* Start button */
start.onclick = function () {
if (!isRunning) {
timer();
isRunning = true;
}
}
/* Stop button */
stop.onclick = function () {
clearTimeout(t);
isRunning = false;
}
/* Clear button */
clear.onclick = function () {
h1.textContent = "03:00:00";
seconds = 0; minutes = 0; hours = 3;
isRunning = false;
}
});
Now modify the BundleConfig.cs file which is normally location in App_Start folder in the project and include the new js file in the bundles collection in RegisterBundles method after all other bundles there like:
bundles.Add(new ScriptBundle("~/bundles/clocker").Include(
"~/Scripts/clocker.js"));
Now in your main view after other scripts include, add include for this script as well:
#{
ViewBag.Title = "Home Page";
}
#using Microsoft.AspNet.Identity
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/clocker")
and now your partial would look like:
<h2><time>03:00:00</time></h2>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
Hope it helps!
I've run the code multiple times trying to fix any error I have found in the code but it just doesn't seem to work.
I'm using the setInterval() loop. The function does not even run once. What could the problem be?
function stopWatch () {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds<60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds.length==2) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes.length==2) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours.length==2) {
document.getElementById('hours').innerHTML = hours;
}
if (hours.length==1) {
document.getElementById('hours').innerHTML = '0' + hours;
}
}
setInterval(stopWatch,1000)
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>
Your code only runs once. You need to use a loop of some description.
There are many ways to do this. A simple example would be to use setInterval to call the inners of your function every second.
You also have an error in your logic. You shouldn't be checking the length of the number (seconds.length==2). You should check wether the number is greater than 9 (seconds > 9):
function stopWatch() {
setInterval(function() {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds < 60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds > 9) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes > 9) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours > 9) {
document.getElementById('hours').innerHTML = hours;
} else {
document.getElementById('hours').innerHTML = '0' + hours;
}
}, 1000);
}
stopWatch()
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>
You mean why the stopwatch is not running?
You should wrap it in a setInteraval for it to update every second:
setInterval(function() {
stopWatch()
},1000);