Pause countdown timer (JavaScript) - javascript

I want the countdown timer to pause when I click the pause button, and start from where it left off when I click the go button. It'd also be good if the go button enables again when reset is clicked, but as of now it continues being disabled for as long as the timer was set.
For pausing, I tried what I saw in this fiddle but it didn't work. I also tried this to no avail:
$("#pause").click(function() {
clearInterval(count());
})
Here's the fiddle.
Thanks!

Here you have solution of working countdown: http://jsfiddle.net/XcvaE/4/
<script>
var CCOUNT = 60;
var t, count;
function cddisplay() {
// displays time in span
document.getElementById('timespan').innerHTML = count;
};
function countdown() {
// starts countdown
cddisplay();
if (count == 0) {
// time is up
} else {
count--;
t = setTimeout("countdown()", 1000);
}
};
function cdpause() {
// pauses countdown
clearTimeout(t);
};
function cdreset() {
// resets countdown
cdpause();
count = CCOUNT;
cddisplay();
};
</script>
<body onload="cdreset()">
<span id="timespan"></span>
<input type="button" value="Start" onclick="countdown()">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset()">
</body>

Related

Countdown timer jquery on reset it runs faster then time set

I am trying to make a countdown timer where I can change the value of the countdown or rest the countdown but I am not able to clear the last timer so the value of the timer is added again to speed if increased please help me I am also sharing the code.
var sec = $("#timer_this").val();
$("#start").click(function() {
var sec = $("#timer_this").val();
startTimer('start');
});
$("#reset").click(function() {
$("#timer").html(0);
var timex = 0;
clearTimeout(timex);
var timex = 0;
startTimer('start');
});
$("#stop").click(function() {
$("#timer").html($("#timer_this").val());
clearTimeout(timex);
});
function startTimer() {
timex = setInterval(function() {
//document.getElementById('timer').innerHTML = sec + "sec left";
$("#timer").html(sec);
sec--;
if (sec == -1) {
clearInterval(timex);
time = null;
alert("Time out!! :(");
}
}, 1000);
}
$("#stopbtn").click(function() {
clearTimeout(timex);
});
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<input type="text" id="timer_this" value="1000">
<span id="timer"></span>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
<button id="reset">reset</button>
several little things to have a working sample :
var timex; should be declared globally if you want to set is value in the several callbacks
in the reset callback you do var timex = 0; first issue you recreate a local function variable timex but you to do it twice that is not valid
for the reset function you can simplyfy it by :
create a stop function
your reset callback became
$("#reset").click(function() {
stopTimer();
startTimer();
});
var sec = $("#timer_this").val();
var timex;
$("#start").click(function() {
var sec = $("#timer_this").val();
startTimer('start');
});
$("#reset").click(function() {
stopTimer();
startTimer();
});
$("#stop").click(stopTimer);
function stopTimer() {
$("#timer").html($("#timer_this").val());
clearTimeout(timex);
timex = undefined;
}
function startTimer() {
if (!timex) {
sec = $("#timer_this").val();
}
timex = setInterval(function() {
$("#timer").html(sec);
sec--;
if (sec == -1) {
clearInterval(timex);
time = null;
alert("Time out!! :(");
}
}, 1000);
}
$("#pause").click(function() {
clearTimeout(timex);
});
<script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<input type="text" id="timer_this" value="1000">
<span id="timer"></span>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
<button id="reset">reset</button>
The timex variable was assigned in the scope of the startTimer function and is lost once that function returns, so it is not available when you later come to call clearTimeout on it.
When building out your logic, its often useful to create functions that describe the actions you want to happen, then call them from your UI components. This helps make the code more readable and reduces repetition.
For example, it's simpler to have clearTimeout in one place, and just call it from whichever methods need to stop the timer. It also helps later when getting the UI to reflect the current state of the application since there's only one way to get to that state.
Here's an example of this sort of approach:
let timerx, sec;
$("#start").click(function() {
// Toggle between start/stop
sec ? stopTimer() : startTimer();
});
$("#pause").click(function() {
// Toggle between pause/resume
timerx ? pauseTimer() : resumeTimer();
});
function startTimer() {
// Stop any existing timer
stopTimer();
// Grab the new count
sec = parseInt($("#timer_this").val());
// Start the timer
resumeTimer();
$("#start").text("stop");
$("#pause").prop("disabled", false);
}
function resumeTimer() {
// Start timer
timerx = setInterval(() => {
// Update time remaining
$("#timer").text(--sec);
if (sec === 0) {
// Handle timeout
stopTimer();
alert("Time out!! :(");
}
}, 1000);
$("#timer").text(sec);
$("#pause").text("pause");
}
function stopTimer() {
// Start timer and clear remainng time
sec = 0;
pauseTimer();
$("#timer").text("");
$("#start").text("start");
$("#pause").prop("disabled", true);
}
function pauseTimer() {
// Just stop the timer
timerx = clearInterval(timerx);
$("#pause").text("resume");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="number" id="timer_this" value="1000">
<button id="start">start</button>
<button id="pause" disabled>pause</button>
<p id="timer"></p>

JavaScript with Timeout Function

I am trying to display a counter at the element with #showText as ID. However, no matter what, the #showText element never appear. I have explanations of the codes below. Can anyone help me to make the #showText element display?
var counter = 0;
// Call the update function 2 seconds after first load.
timeoutID = window.setTimeout("Update();", 2000);
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHtml = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout("Update();", 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
change setTimeout("Update();", 2000) to setTimeout(Update, 2000)
change innerHtml to innerHTML
var counter = 0;
// Call the update function 2 seconds after first load.
timeoutID = window.setTimeout(Update, 2000);
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHTML = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout(Update, 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
Your textField.innerHTML had a syntax error; you wrote innerHtml. I also removed the orphan function call, as you would want it to only run on button press I presume. Correcting that, now it works -the STOP button as well -:
var counter = 0;
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHTML = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout("Update();", 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
You can:
use setInterval rather than setTimeout;
innerHTML or innerText rather than the (invalid) innerHtml;
separate out the logic for starting, stopping, showing the counter and updating the counter to make it clearer what is being run and when and to make sure you do not have additional timers spawned:
var counter = 0;
var isCounting = false;
var timeoutID = null;
var textField = document.getElementById("showText");
function Stop() {
if ( timeoutID )
{
self.clearInterval( timeoutID );
}
}
function Start()
{
Stop();
counter = 0;
timeoutID = self.setInterval(Update, 2000);
Show();
}
function Show()
{
textField.innerText = counter;
}
function Update() {
counter++;
Show();
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", Start );
document.getElementById("stop").addEventListener("click", Stop );
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
There is only a single change that has to be done in you code to make it work as expected.
Just replace the below function block and run the code:
function Update() {
counter++;
document.getElementById("showText").innerHTML = "The counter is now at!" + counter;
timeoutID = window.setTimeout("Update();", 2000);
}
this solution should work for you.

How to create automatic Refresh when Checkbox is clicked?

I want to create automatic refresh when check box click. countdown timer running well but still no luck when I click the checkbox
this is my code. need help to review my code
// COUNTDOWN METHOD.
window.setInterval(function() {
counter--;
if (counter >= 0) {
var span;
span = document.getElementById("cnt");
span.innerHTML = counter;
}
if (counter === 0) {
clearInterval(counter);
}
}, 1000);
window.setInterval('refresh()', 10000);
// REFRESH OR RELOAD PAGE.
function refresh() {
window.location.reload();
}
<input type="checkbox"> This page will reload in <span id="cnt" style="color:red;">30</span> Seconds
Add an onclick handler:
<input type="checkbox" onclick="refresh()">
In the html, call a function which should be getting executed on checkbox selection
<input type="checkbox" id="myCheck" onclick="checkboxClicked()"> This page will reload in <span id="cnt" style="color:red;">30</span> Seconds
In javasccript function start the timer and call refresh after 30sec.
function checkboxClicked() {
//function gets called when the checkbox is clicked and the counter starts
let counter = 30
window.setInterval(function() {
counter--;
if (counter >= 0) {
var span;
span = document.getElementById("cnt");
span.innerHTML = counter;
}
if (counter === 0) {
clearInterval(counter);
}
}, 1000);
window.setInterval('refresh()', 30000);
}
// REFRESH OR RELOAD PAGE.
function refresh() {
window.location.reload();
}

Manually set interval time for setInterval

I'm trying to create application where the user can select how often they want the counter to increment by. For example, they type into the input box that they want it to increment by 1 every 5 seconds, and the setInterval will be set to 5 seconds, etc. Here's what I have so far:
<input type="text" id="timer"></input>
<input type="button" onlick="setTime()" value="test" />
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
<script type="text/javascript">
function setTime() {
var output = $('h1');
var isPaused = true;
var count = 0;
timer = document.getElementById("timer").value;
setInterval(function() {
if(!isPaused) {
time++;
output.text(time);
}
}, timer*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
isPaused = true;
});
$('.play').on('click', function(e) {
e.preventDefault();
isPaused = false;
});
</script>
Can I get any ideas or help? I appreciate it in advance
Refactoring a little your code, you can do it this way:
Every <input type="text" id="timer"></input>Seconds<br>
<button class="start">Start</button>
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
And the JS:
var interval = null;
var time = 0;
var output = $('h1');
function setTimer() {
var seconds = +($("#timer").val());//Get the user input (and convert to number)
interval = setInterval(function() {
time++;
output.text( time );
}, seconds*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
if(interval){
clearInterval(interval);//Clear the created interval
}
});
$('.play').on('click', function(e) {
e.preventDefault();
setTimer();
});
$('.start').click(function(){
time = 0;
setTimer();
});
See the working example here: https://output.jsbin.com/cukehijuwo/
Each time the user calls setTime, you are creating another interval. These will continue to be created throughout the lifecycle of your application. You should remove timeouts before creating new ones:
var timeoutID = null;
function setTime() {
...
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
...
}, timer * 1000);
}
For reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Full simple tested program, hope this will help you
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
function display() {
$("h1").html(parseInt($("#inc").val()) + parseInt($("h1").html())) ;
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
function pauseT(){
clearTimeout(t);
}
function continueT(){
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
</script>
Increment Value<input type="text" id="inc"></input>
Interval in Second<input type="text" id="int"></input>
<input type="button" onclick="display()" value="Start" />
<h1>0</h1>
<button onclick="continueT()">Continue</button>
<button onclick="pauseT()">Pause</button>

Start and Stop timer not working

I am trying to make a timer that starts when you click the top button and stops and resets when you click the bottom button. Here is a link to my fiddle http://www.jsfiddle.net/AbrGL/
My HTML:
<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startclock()"/>
<div id="timer">0</div>
<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopclock()"/>
My JavaScript:
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
}
else if (clicked === true) {
}
}
function stopWatch() {
sec+;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=0;
clicked = false;
}
Ok you have a lot of typos.
First, sec+; does not do anything. It should be sec++;.
Second, your onClick properties point to startclock() and stopclock(), which should actually be startClock() and stopClock(). Function names are case-sensitive in JavaScript.
Third, the clicked variable is undefined so startClock() will never actually do anything. Add var clicked = false; before your function declarations.
Last but not least, sec is undefined, so incrementing it doesn't make sense. Add var sec = 0; before your function declarations.
HTML should look like
<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startClock()"/>
<div id="timer">0</div>
<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopClock()"/>
and JavaScript should look like
var clicked = false;
var sec = 0;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
}
else if (clicked === true) {
}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=0;
clicked = false;
}
Here is a working fiddle with the changes above: http://jsfiddle.net/AbrGL/8/
In the "stopWatch()" method, Replace sec+; with sec++;
I also found some typos, JavaScript is a CaSe SeNsitIvE language
I've made a few changes dom and js
HTML
<input type="button" id="start-clock" value="Click here to start timer"/>
<div id="timer">0</div>
<input type="button" id="stop-clock" value="Click here to stop and reset the timer"/>
JS
var clock;
var sec = 0;
document.getElementById("start-clock").addEventListener("click",function(){
clock = setInterval(stopWatch,1000);
},false);
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
document.getElementById("stop-clock").addEventListener("click",function(){
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=sec;
},false);
and have a look at jsFiddle
Try this one :
http://tutorialzine.com/2015/04/material-design-stopwatch-alarm-and-timer/
this is the best i have ever used, you can make little changes accordingly if required.

Categories

Resources