how can activate my countdown timer with button? - javascript

I have a countdown timer function writed in javascript.Its working but it starts when i start the page.I want it should be start when the button clicked.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
// timer = 0;
time.style.display = "none";
time2.style.display2 = "none";
redxsms.style.display = "none";
onaysms.style.display = "none";
tekraruyarionay.style.display = "block";
tekraruyarired.style.display = "block";
// time.style.display="block";
setTimeout(function () { location.reload() }, 5000);
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
this is the countdown function.
<button class="ui toggle button" onclick=" hideshow(document.getElementById('onaysms')); show(this);" id="onaytoggle">
this is button when i click it should activate.
<span id="time"></span>
It starts when the page start how can i start when the button clicked?

Insert your timer call in an "onclick" event like this, it will be fired when you click on the button.
If you have several buttons on your page, i would advise you to give one an id by adding this in your html : id='timerToggle' and then replacing the $("button.toggle") in the code below by $("#timerToggle")
jQuery(function ($) {
$("button.toggle").click(function(){
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
});

Related

Javascript Stopwatch. Need help to store my timer and when page refresh to keep the time and continue from there

I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.
let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
showTime.innerHTML = `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "block";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
// Pause function
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "block";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>
You could use localStorage.
In order to save each second passed you could modify your timer function to save to localStorage:
let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}
//...
const timer = () => {
//...
seconds++;
localStorage.setItem("stopwatchSeconds", seconds);
//...
};
//...
I hope this helps.
It seems like what you're looking for is localStorage. You store your stopwatch data, such as startAt, totalSeconds in the storage and when you refresh the page you can restore your stopwatch state based on the saved data: remainingTime = (startAt + totalSeconds) - currentTime
localStorage docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage#storing_simple_data_%E2%80%94_web_storage

Submit the value of a timer which is then use for JS function

I am trying to enable the user to set the value of a timer and then to see the countdown timer displayed on the webpage.
Here is my HTML code:
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" name="submit" class="submit" value="Submit">
And here is my JS code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
jQuery(function ($) {
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
});
This code is working because in the HTML file, I hardcoded the value to 3 minutes directly.
But I would like to remove this value="3"and be able to set it up manually in the input field.
But when I am doing that, the timer is not displayed.
First, you should add the 'id'-attribute to the input element:
<input type="submit" name="submit" class="submit" value="Submit" id="submit">
But just setting the function glitches out the timer if the user inputs multiple values, so you should change your code like this:
var clearIntervalId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
clearIntervalId = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
$("#submit").click(function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
if (typeof clearIntervalId !== 'undefined') {
clearInterval(clearIntervalId)
}
startTimer(myVar, display);
});
clearIntervalId is used, so that the previous running setInterval()-function is getting cleared out everytime the user clicks the button, so that there won't be interfering changes in the current minutes + seconds.
What do you need is a trigger for the startTimer function after event
and in your code the event is a button click
Add id attribute to your button
<input type="submit" id="submit" name="submit" class="submit" value="Submit">
and add click event listener to your button
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
jQuery(function ($) {
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
});
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" id="submit" name="submit" class="submit" value="Submit">

Javascript function only starts when page is reloaded manually

I have a function that works as it should, but only if the page is reloaded after landing on the specific page.
The function is a timer function that starts to tic down from 10 to 0 when the page is loaded (it should work like this).
But I land on the page and nothing happens. When I reload the page the timer starts and works...
I have tried $(document).on and window.onload = function() but with no success.
FlowRouter.route("/waitingForPlayer", {
name: "waitingForPlayer",
action() {
BlazeLayout.render("iphone", { main: "waitingForPlayer" });
console.log("first");
window.onload = startTimer;
function startTimer(duration, display) {
console.log("second");
var timer = duration,
seconds;
setInterval(function() {
console.log("third");
seconds = parseInt(timer % 60, 10);
seconds = seconds < 10 ? "" + seconds : seconds;
display.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (timer == 0) {
FlowRouter.go("readyForGame");
document.location.reload(true);
}
}, 1000);
}
window.onload = function() {
var fiveMinutes = 10,
display = document.querySelector("#time");
startTimer(fiveMinutes, display);
};
}
});
When the timer is = 0 the flowrouter changes view.
I think the problem is that you put onload function inside the router callback. You don't need to run window.onload inside router's callback because it's Single page application router. Try to look for onComplete event of the flow-router library. I think that action is the callback for complete event of the router.
Example:
function startTimer(duration, display) {
console.log("second");
var timer = duration, seconds;
setInterval(function() {
console.log("third");
seconds = parseInt(timer % 60, 10);
seconds = ('0' + seconds).slice(-2);
display.innerText = seconds;
if (--timer < 0) {
timer = duration;
}
if (timer == 0) {
FlowRouter.go("readyForGame");
}
}, 1000);
}
FlowRouter.route("/waitingForPlayer", {
name: "waitingForPlayer",
action: function() {
BlazeLayout.render("iphone", { main: "waitingForPlayer" });
console.log("first");
var fiveMinutes = 10,
display = document.querySelector("#time");
startTimer(fiveMinutes, display);
}
});

How to stop JavaScript Timer?

I have a simple Bootstrap page that includes a 45 second countdown timer and a button which I intend to include on a bigger project later. The countdown timer will start on a click of the button.
What I wanted to do is that when I click on the button again within the 45 seconds countdown interval, the counter will reset. I am not able to do that. What I tried to do is to use the clearInterval function at the very beginning of the errorTimer function. But, it did not work.
Here are my codes:
// Timer for error message - 45 seconds.
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>
Use clearInterval like this
...
// Timer for error message - 45 seconds.
var timerId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if(timerId != undefined) {
clearInterval(timerId)
}
timerId = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function errorTimer () {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
...
As #Shidersz mentioned, you need to store the id associated with the interval and use that id to clear the interval before resetting the clock.
// Timer for error message - 45 seconds.
var id = null;
function startTimer(duration, display) {
if (id !== null) {
clearInterval(id);
id = null;
}
var timer = duration,
minutes, seconds;
id = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>
You could stop the timer by clearing the interval:
// Timer for error message - 45 seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var interval = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
return function(){ clearInterval(interval); };
}
function errorTimer () {
var fortyFiveSeconds = 60 * .75,
var display = document.querySelector('#time');
var stopper = startTimer(fortyFiveSeconds, display);
setTimeout(stopper, 20 * 1000); // stop timer 20 seconds later.
};
I make use of a simple function returned by the startTimer function, that can be used to clear the interval at a later point.

how do i auto-submit the form when the timer comes to 00:00:00

I have used a countdown timer in my online examination website,the timer is shown via javaScript but problem is that after the 00:00:00 the timer shows negative time.I just want to stop the timer at 00:00:00 and submit a form when the time is over.below is the code that accurately displaying me the timer.
<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>
<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');
</script>
<script type="text/javascript">
function countdownto() {
var date = Math.round((TimeLimit-new Date())/1000);
var hours = Math.floor(date/3600);
date = date - (hours*3600);
var mins = Math.floor(date/60);
date = date - (mins*60);
var secs = date;
if (hours<10) hours = '0'+hours;
if (mins<10) mins = '0'+mins;
if (secs<10) secs = '0'+secs;
document.body.innerHTML = hours+':'+mins+':'+secs;
setTimeout("countdownto()",1000);
if((hours==00)&&(mins==00)&&(secs==00))
document.alert("time is over");
}
countdownto();
</script>
I assume that your form has an ID attribute with this value yourForm.
// HTML
<form id="yourForm">[...]</form>
// JS
if((hours==00)&&(mins==00)&&(secs==00)) {
document.getElementById('yourForm').submit();
} else {
setTimeout(countdownto, 1000);
}
Note: Remove your setTimeout(countdownto, 1000); before the if statement
Alternative way.
You could kill the timeout with clearTimeout()
var myTimeout = setTimeout(countdownto, 1000);
if((hours==00)&&(mins==00)&&(secs==00)) {
clearTimeout(myTimeout);
document.getElementById('yourForm').submit();
}
clearTimeout documentation
Let's create a index.php file please check it. form submit on timer you can pass time through in javascript CountDown(5,div); function.
<html>
<body>
<form action="" method="post" name="mcQuestion" id="mcQuestion">
Name:<input type="test" name="name" value="Test">
<div><span id="display" style="color:#FF0000;font-size:15px"></span></div>
<div><span id="submitted" style="color:#FF0000;font-size:15px"></span></div>
</form>
<script>
var div = document.getElementById('display');
var submitted = document.getElementById('submitted');
function CountDown(duration, display) {
var timer = duration, minutes, seconds;
var interVal= setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML ="<b>" + minutes + "m : " + seconds + "s" + "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
SubmitFunction();
}
},1000);
}
function SubmitFunction(){
submitted.innerHTML="Time is up!";
document.getElementById('mcQuestion').submit();
}
CountDown(5,div);
</script>
</body>
</html>

Categories