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>
Related
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>
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>
I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>
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.
Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.
As you asked for a method using setTimeout:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);
Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.
Use setInterval:
var timeOut = setInterval(nextNotice, 5000);
var myFunction = function() {
//Do stuff
AnotherFunction();
};
var timeOut = setInterval(myFunction, 2000);
you can do something like:
$(document).ready(function ()
{
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff
setTimeout(nextNotice, 5000);
}
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
<html>
<head>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = false;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(timedCount, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = true;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>