I am running the JavaScript timer using setInterval(). I want to run the timer for 5 seconds then restart the timer from zero seconds and the same process should run for 3 times.
<!DOCTYPE html>
<html>
<head>
<title>Jquery setinterval stop after sometime</title>
</head>
<body>
<p>Counter: <span id="counter"></span></p>
<p>Seconds: <span id="seconds"></span></p>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var start_secs;
var counter = 0;
function intervalFunc(){
var seconds = 0;
$('#counter').html(counter);
start_secs = setInterval(function(){
$('#seconds').html(seconds);
if(seconds===5){
if(counter < 3){
intervalFunc();
}else{
console.log('else');
clearInterval(start_secs);
seconds=0;
return false;
}
}
seconds++;
}, 1000);
counter++;
}
intervalFunc();
});
</script>
</body>
The above code timer works fine until counter value is less than 3 but after that setInterval() keeps running and doesn't stop even on using clearInterval().
Can anyone point out the problem in the given code that why setInterval() is not stopping after counter value is greater than or equal to 3 ?
There are a few problems. The main one is that start_seconds needs to be local to the function rather than declared outside the function — you want to control each interval independently within the function. The way you have it, you lose the references to the earlier timers. And you want to clear the interval when seconds == 5 regardless of whether the counter < 3 because you are starting a new one.
Something like this:
var counter = 0;
function intervalFunc(){
var seconds = 0
var start_secs = setInterval(function(){
console.log(seconds)
if(seconds===5){
if(counter < 3){
intervalFunc();
}
// after 5 times clear the interval
// a new one is started if counter < 3
clearInterval(start_secs);
return
}
seconds++;
}, 500);
counter++;
}
intervalFunc();
Before calling the intervalFunc() you must clear your previous timer. Because every timer is assigned to the same variable, so the timer is running in the background and then there is no way to clear those timers.
Check the code with the changes:
<!DOCTYPE html>
<html>
<head>
<title>Jquery setinterval stop after sometime</title>
</head>
<body>
<p>Counter: <span id="counter"></span></p>
<p>Seconds: <span id="seconds"></span></p>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var start_secs;
var counter = 0;
function intervalFunc(){
var seconds = 0;
$('#counter').html(counter);
start_secs = setInterval(function(){
$('#seconds').html(seconds);
if(seconds===5){
clearInterval(start_secs);
if(counter < 3){
intervalFunc();
}else{
console.log('else');
seconds=0;
return false;
}
}
seconds++;
}, 1000);
counter++;
}
intervalFunc();
});
</script>
</body>
you only need to call setInterval once because it will continue running before you stop it.
$(document).ready(function() {
var start_secs;
var counter = 0;
var seconds = 0;
function intervalFunc() {
if (seconds === 5) {
seconds = 0;
counter++;
if (counter == 3) {
// seconds = 5; // uncomment to show 5 instead of 0 when finished
clearInterval(start_secs);
console.log('Finish');
}
}
else {
seconds++;
}
$('#seconds').html(seconds);
$('#counter').html(counter);
}
start_secs = setInterval(intervalFunc, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Counter: <span id="counter">0</span></p>
<p>Seconds: <span id="seconds">0</span></p>
As you may know now after the previous answers, you are calling setInterval many times thus creating many intervals that are impossible to clear.
When you are calling the intervalFunc again inside it, it goes through the setInterval line and sets another Interval. Thus creating many intervals until the counter reaches 5 and clears ONLY ONE interval after the conditioning fails. Here is a tested code that can do it without any issues:
$(document).ready(function() {
var start_secs;
var counter = 0;
var seconds = 0;
$('#counter').html(counter);
$('#seconds').html(seconds);
function increaseCounter(){
counter+=1;
$('#counter').html(counter);
}
var start_secs = setInterval(function(){
if(seconds==5){
seconds=0;
if(counter < 3){
increaseCounter();
}
else if(counter==3){
counter=0;
seconds=0;
$('#counter').html(counter);
$('#seconds').html(seconds);
clearInterval(start_secs);
}
}
$('#seconds').html(seconds);
seconds+=1;
}, 1000);
});
Tested it and it's working. I hope it works for you...
Related
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...
$(document).ready(function(){
$("#start").click(function(){
for(var i = 0; i < 5; i++){
setTimeout(function(){
console.log("hello world")
},5000)
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?
You can use a for loop, but you need to give different timeouts so they'll run at different times.
$(document).ready(function(){
$("#start").click(function(){
for(var i = 0; i < 5; i++){
setTimeout(function(){
alert("hello world")
}, 5000 * (i + 1))
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
Please check below mentioned solution.
var i = 1;
var interval = setInterval(
function(){
if(i<=5){
alert('Hello World!');
i++;
}else{
clearInterval(interval);
}
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Let me know if it not works
I've updated the answer using setInterval and instead of for loop you can pass data runTimer method
function runTimer(callback, delay, repeat) {
var i = 0;
var timer = setInterval(function () {
callback();
i++;
if (i == repeat) clearInterval(timer);
}, delay);
}
$(document).ready(function(){
$("#start").click(function(){
runTimer(function(){
alert('hello')
}, 5000, 5);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">
start
</button>
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);
I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});
<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle
I want implement timer using java script.I want to decrement timer with variation of interval.
Example.Suppose my timer starts at 500 .
I want decrement timer depending on the level such as
1. 1st level timer should decrement by 1 also decrement speed should be slow.
2.2nd level timer should decrement by 2 and decrement speed should be medium
3.3rd level timer should decrement by 3 and decrement speed should be fast
I can create timer using following code:
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
TotalSeconds=Time;
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer();
setTimeout("Tick()", 1000);
}
function Tick() {
TotalSeconds -= 10;
if (TotalSeconds>=1)
{
UpdateTimer();
setTimeout("Tick()", 1000);
}
else
{
alert(" Time out ");
TotalSeconds=1;
Timer.innerHTML = 1;
}
}
But i call this CreateTimer() function many times so its speed is not controlling because i call it many times.
Couple of points:
You've used all global variables, it's better to keep them private so other functions don't mess with them
Function names starting with a captial letter are, by convention, reserved for constructors
The function assigned to setTimeout doesn't have any public variables or functions to modify the speed while it's running so you can only use global variables to control the speed. That's OK if you don't care about others messing with them, but better to keep them private
The code for UpdateTimer hasn't been included
Instead of passing a string to setTimeout, pass a function reference: setTimeout(Tick, 1000);
Anyhow, if you want a simple timer that you can change the speed of:
<script>
var timer = (function() {
var basePeriod = 1000;
var currentSpeed = 1;
var timerElement;
var timeoutRef;
var count = 0;
return {
start : function(speed, id) {
if (speed >= 0) {
currentSpeed = speed;
}
if (id) {
timerElement = document.getElementById(id);
}
timer.run();
},
run: function() {
if (timeoutRef) clearInterval(timeoutRef);
if (timerElement) {
timerElement.innerHTML = count;
}
if (currentSpeed) {
timeoutRef = setTimeout(timer.run, basePeriod/currentSpeed);
}
++count;
},
setSpeed: function(speed) {
currentSpeed = +speed;
timer.run();
}
}
}());
window.onload = function(){timer.start(10, 'timer');};
</script>
<div id="timer"></div>
<input id="i0">
<button onclick="
timer.setSpeed(document.getElementById('i0').value);
">Set new speed</button>
It keeps all its variables in closures so only the function can modify them. You can pause it by setting a speed of zero.
Hope, this could be helpful:
<html>
<head>
<script type="text/javascript">
function showAlert()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Time up!!!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Start" onClick="timeMsg()" />
</form>
</body>
</html>
Check this demo on jsFiddle.net.
HTML
<div id="divTimer">100</div>
<div id="divDec">1</div>
<div id="divSpeed">100</div>
<input id="start" value=" Start " onclick="javaScript:start();" type="button" />
<input id="stop" value=" Stop " onclick="javaScript:stop();" type="button" /><br/>
<input id="inc" value=" Increase " onclick="javaScript:increase();" type="button" />
<input id="dec" value=" Decrease " type="button" onclick="javaScript:decrease();"/>
JavaScript
var handler;
function start() {
handler = setInterval("decrementValue()", parseInt(document.getElementById('divSpeed').innerHTML, 10));
}
function stop() {
clearInterval(handler);
}
function decrementValue() {
document.getElementById('divTimer').innerHTML = parseInt(document.getElementById('divTimer').innerHTML, 10) - parseInt(document.getElementById('divDec').innerHTML, 10);
}
function increase() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) + 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) + 200;
stop();
decrementValue();
start();
}
function decrease() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) - 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) - 200;
stop();
decrementValue();
start();
}
Hope this is what you are looking for.