Currently I have a timer that counts down from two minutes. What i need is a button that will stop and reset the timer. Here is the code i have.
js
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
var intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
HTML
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
here is a working code pen of the timer but not the color change http://codepen.io/Chevex/pen/RNomGG
Try ...
HTML:
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
<button id="stopTimer" disabled>Stop and Reset Timer</button>
JS:
$(function () {
var $startTimer = $('#startTimer');
var $stopTimer = $('#stopTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
var intervalId;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$stopTimer.prop('disabled', false);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining / 60) + ':' + timeRemaining % 60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
$stopTimer.click(function() {
time = 120;
$startTimer.prop('disabled', false);
$stopTimer.prop('disabled', true);
$timerDisplay.hide();
clearInterval(intervalId);
$timerDisplay.text("");
});
});
Basically, I moved the interval variable and created a stop timer button; the click functionality performs the reset, using the code similar to what you performed before.
jsFiddle: http://jsfiddle.net/rfornal/w29ofkek/
create a input button as follows
<input type='button' value="Stop" onclick="StopTimer();"/>
Change your code to following
var intervalId =null;
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
function StopTimer()
{
clearInterval(intervalId);
}
Related
Please help me! I make some simple app for bike renting in local storage. How to alert("Expired") when counter reach zero. When i put alert inside setInterval method, i have repeating alert evry second.
var interval = 5000;
function reset() {
localStorage.endTime = +new Date + interval;
}
if (!localStorage.endTime) {
reset();
}
var remaining = localStorage.endTime - new Date;
setInterval(brojanje, 100)
function brojanje() {
if (remaining > 0) {
$('#timer').text(Math.floor(remaining / 1000));
} else {
return;
}
}
<div Time remaining: <span id="timer">
</span>
</div>
<button onclick="reset()">Click me</button>
You need to stop your timer using clearInterval function.
var interval = setInterval(brojanje, 100);
function brojanje() {
if (remaining > 0) {
$('#timer').text(Math.floor(remaining / 1000));
} else {
console.log('Alert and kill timer');
alert('STOP!');
clearInterval(interval);
}
}
Here's a version I worked on. I removed the use of jquery too.
<script>
let duration = 5000
let end_time = 0
let the_interval
function reset () {
end_time = Date.now() + duration
localStorage.endTime = end_time
}
function start_interval () {
clearInterval(the_interval)
let timer = document.querySelector("#timer")
the_interval = setInterval(function () {
let remaining = end_time - Date.now()
if (remaining <= 0) {
clearInterval(the_interval)
return
}
timer.textContent = Math.floor(remaining / 1000)
}, 100)
}
window.onload = function () {
document.querySelector("#reset_button").addEventListener("click", function () {
reset()
start_interval()
})
end_time = parseInt(localStorage.endTime)
start_interval()
}
</script>
<span>Time remaining:</span> <span id="timer"></span></div>
<button id="reset_button">Click me</button>
I'm trying to make my countdown timer do the following 4 things
When 'start' is clicked, change button to 'stop'
When 'stop' is clicked, stop the timer
When timer is stopped, show 'start' button
When 'reset' is clicked, reset the timer
$(document).ready(function() {
var counter = 0;
var timeleft = 5;
function nf(num) {
var s = '0' + num;
return s.slice(-2);
}
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ' ' + nf(sec, 2);
}
function setup() {
var timer = document.getElementById("timer");
timer.innerHTML = (convertSeconds(timeleft - counter));
var interval = setInterval(timeIt, 1000);
function timeIt() {
counter++;
timer.innerHTML = (convertSeconds(timeleft - counter));
if (counter == timeleft) {
clearInterval(interval);
}
}
}
$("#timer-button").click(function() {
setup();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I recently needed something like this too. I ended up writing an ES6 class for that.
In my solution, I used Events to notify other components about the timer. Here is a fiddle in which I met your needs, but I left my EventManager() calls to show what I actually did.
The used EventManager is this one. The timer counts in 100ms steps by default, but you can adjust this by calling startTimer() with the interval of choice.
class Timer {
constructor(maxTime, startValue = 0) {
// Actual timer value 1/10s (100ms)
this.value = startValue;
// Maximum time of the timer in s
this.maxTime = maxTime * 10;
this.timerRunning = false;
}
/**
* Starts the timer. Increments the timer value every 100ms.
* #param {number} interval in ms
*/
startTimer(interval = 100) {
if (!this.timerRunning) {
let parent = this;
this.timerPointer = setInterval(function() {
if (parent.value < parent.maxTime) {
parent.value++;
//EventManager.fire('timerUpdated');
$("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
} else {
parent.stopTimer();
//EventManager.fire('timeExceeded');
$("button").text("Start");
this.resetTimer();
$("span").text("Countdown over");
}
}, interval);
this.timerRunning = true;
}
}
// Stops the Timer.
stopTimer() {
clearInterval(this.timerPointer);
this.timerRunning = false;
}
// Resets the timer and stops it.
resetTimer() {
this.stopTimer();
this.value = 0;
$("span").text("0/" + this.maxTime/10);
//EventManager.fire('timerUpdated');
}
// Resets the timer and starts from the beginning.
restartTimer() {
this.resetTimer();
this.startTimer();
}
}
let timer = new Timer(6);
$("#start-stop").click(function() {
if (timer.timerRunning) {
timer.stopTimer();
$("#start-stop").text("Start");
} else {
timer.startTimer();
$("#start-stop").text("Stop");
}
});
$("#reset").click(function() {
timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>
const div = document.querySelector('div');
const btn = document.querySelector('#timerBtn');
const resetbtn = document.querySelector('#reset');
let startFlag = 0;
let count = 0;
let intervalId;
const ms = 1000;
div.textContent = count;
btn.addEventListener('click', function() {
startFlag = startFlag + 1;
if(startFlag%2 !== 0) { // Start button clicked;
btn.textContent = 'Stop';
startTimer();
} else {
btn.textContent = 'Start';
stopTimer();
}
});
resetbtn.addEventListener('click', function() {
count = 0;
div.textContent = count;
});
function startTimer() {
intervalId = setInterval(() => {
count = count + 1;
div.textContent = count;
}, 1000);
}
function stopTimer() {
clearInterval(intervalId);
}
<div></div>
<button id="timerBtn">Start</button>
<button id="reset">Reset</button>
I am working with JavaScript and I use a setTimeout function in order to count up. Here is my code...
<button id="star">Start</button>
<p id="time">0</p>
var timeEl = 0;
function start() {
time();
}
function time() {
setTimeout(function() {
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", star, false);
How do I get my setTimeout function to start on stop when I click on the button
How to prevent my counting from going faster the more times I click on the button.
I have included my JSFiddle below!
https://jsfiddle.net/pb4759jh68/0618eLoe/
To stop a timer you can use clearTimeout(), but it does require the id of the timer created with setTimeout(). The call to setTimeout() now saves the timer id in timeOut and then checks the contents of timeOut in start() to see whether a timer is currently running. If a timer is running then timeOut is used in clearTimeout(timeOut);.
var timeEl = 0;
var timeOut = null;
function start()
{
if(timeOut !== null){
clearTimeout(timeOut);
timeOut = null;
}else{
time();
}
}
function time()
{
timeOut = setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
I hope this code clears the issue
JSFiddle
The same can be achieved using setInterval and clearInterval. Try this JSFiddle
Every time the button is pressed, you get a second copy of your timer running, which is advancing your time faster.
var el = document.getElementById("star");
el.addEventListener("click", start, false);
I would recommend something like this:
var timerId = 0;
var timeEl = 0;
function start()
{
time();
}
function time()
{
timerId = setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", function() {
if (timerId !== 0) {
clearTimeout(timerID);
timerId = 0;
} else {
start();
}
}, false);
You can cancel a previously set timeout with clearTimeout - see https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout.
try this
JsFiddle
var timeEl = 0,timer;
function start()
{
time();
}
function time()
{
document.getElementById("star").disabled=true;
timer=setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
function stop(){
document.getElementById("star").disabled=false;
clearTimeout(timer);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
var elstop = document.getElementById("stop");
elstop.addEventListener("click", stop, false);
I simply added a boolean that states if the counting is already running :
https://jsfiddle.net/0618eLoe/3/
var timeEl = 0;
var isStarted = false;
function startStop()
{
if (!isStarted) {
isStarted = true;
time();
} else {
isStarted = false;
}
}
function time()
{
if (!isStarted) return;
setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", startStop, false);
The following is a simple solution using setInterval and clearInterval
var time = 0.0;
var view = document.getElementById('time');
var running = false;
var repeat;
function start(){
if(running){
return;
}
running = true;
repeat = setInterval(increment, 100);
}
function stop(){
clearInterval(repeat);
running = false;
}
function increment(){
time += 0.1;
view.innerText = time.toFixed(1);
}
Demo:
https://jsfiddle.net/m7bmc2uj/
var timeEl = 0,g;
function start()
{
if(g){
clearTimeout(g);
timeEl = 0;
}
time();
}
function time()
{
g=setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
tell me what else would you need. or it implements your specification. here button click will start the timer from 0 again.
jsfiddle
If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()
I have this countDown, each time I press the buttons I want to add 5 more seconds.
When the time is updated the function count down the new value but the old value as well.
Can someone explain me why?
http://jsfiddle.net/xqdj3uz8/1/
$('button').on('click', function() {
var newtime = parseInt(seconds + 5);
timer(newtime);
});
You could try by using a global variable to track the amount of seconds left. Clicking on the button will increment this variable.
var timeLeft = 10;
function timer() {
var i = setInterval(function () {
$('span').text(timeLeft);
timeLeft--
if (timeLeft === 0) clearInterval(i)
}, 1000)
}
function addSeconds(n) {
timeLeft += n
}
timer()
$('button').on('click', function () {
addSeconds(5)
});
Demo (1): http://jsfiddle.net/xqdj3uz8/21/
please use it
function timer(time) {
var interval = setInterval(countDown, 1000);
function countDown() {
time--;
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
}
$('button').on('click', function() {
time=parseInt(time + 5);
$('span').text(time);
});
}
var seconds = 5;
timer(seconds);
Try This
Working JSFIDDLE
var gblTime=0;
function timer(time) {
var interval = setInterval(countDown, 1000);
gblTime = time;
function countDown() {
gblTime--;
$('span').text(gblTime);
if(gblTime <= 0) {
clearInterval(interval);
}
}
}
var seconds = 5;
timer(seconds);
$('button').on('click', function() {
gblTime = parseInt(gblTime +1+ 5);
//timer(newtime);
});
You are adding new intervals that are independent form each other, try:
var time = 5;
var seconds = 5;
function timer() {
var interval = setInterval(countDown, 1000);
function countDown() {
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
time--;
}
}
timer();
$('button').on('click', function() {
if(time==0){
timer();
}
time += seconds;
});