How to initiate this timer with an image button? - javascript

I have a 30 second timer and an image. I want the timer to only commence when the image is clicked, i.e. an image button - how do I go about this?
This is how I currently have the timer, with displays on the page itself:
<h2>Countdown left: <span id="timer"></span></h2>
And this is the image:
<img id="img" src="image.gif" />
My timer is JS:
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
How can I combine the two?

You can add click event listener to the image, which will initiate the timer. Also, I have added {once: true} so that the function would execute only once (else it will bug out the timer).
document.querySelector("#img").addEventListener("click", () => {
var countdown;
var seconds = 30;
countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
},{ once: true});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />
If you want to reset the timer on each click, you need to clearInterval before setting another.
var countdown;
document.querySelector("#img").addEventListener("click", () => {
if (countdown) {
clearInterval(countdown);
}
var seconds = 30;
countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds <= 0) clearInterval(countdown);
}, 1000)
});
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://assets.stickpng.com/thumbs/59060d740cbeef0acff9a660.png" />

let timer;
const onClick = () => {
// Initial seconds
let count = 30;
// Element where the count down needs to be displayed
const element = document.querySelector('#timer');
// Remove the timer if it already exists. This would be helpful
// in case the user clicks again on the image. When User clicks
// again on the image, the existing timer is reset
if (timer) {
clearInterval(timer);
}
//Display the initial value i.e. 30 in this case
element.textContent = count;
//Decrease the timer by a second using setInterval
timer = setInterval(() => {
count -= 1;
// If counter is less than or equal to zero, then
// remove the existing count down and perform the logic
// of what should happen when the count down completes
if (count <= 0) {
clearInterval(timer);
element.textContent = '';
return;
}
element.textContent = count;
}, 1000);
}
// Attaches the click event on the image
const image = document.querySelector('#img');
if (image) {
image.addEventListener('click', onClick)
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="https://picsum.photos/200" />

If you wrap your existing js in a function, you can add it as a method for the click event listener on the button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" />
<script>
function count(){
var seconds = 30;
var countdown = setInterval(function() {
document.getElementById("timer").textContent = seconds;
seconds--;
if (seconds < 0) clearInterval(countdown);
}, 1000);
}
document.getElementById('img').addEventListener('click', count)
</script>
</body>
</html>

i think you need to create one function on click of image :
HTML
<img id="img" src="image.gif" onclick="StartTimer()" />
<script type="text/javascript">
function StartTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("countdown").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
</script>

function startTimer() {
var seconds = 30;
var countdown = setInterval(function() {
seconds--;
document.getElementById("timer").textContent = seconds;
if (seconds <= 0) clearInterval(countdown);
}, 1000);
}
<h2>Countdown left: <span id="timer"></span></h2>
<img id="img" src="image.gif" onClick="startTimer()" />
You can try wrapping the setInterval in a function and call that function on click of image

Related

How to handle timer button to not to display negative values on click?

I have a button.
After clicking on it , 10 seconds timer starts on button with changing text.
When i click in between the timer it decrements the value by one.
And at the last shows negative value.
Also when timer becomes zero and i click button it becomes-1 , -2
It should not go below zero.
Tried by many ways but couldn't solve the issue
Here is my code
timeLeft = 10;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) {
setTimeout(countdown, 1000);}
};
function timer(){
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
$("#tmp_button-72286").bind("click", (function () {
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
With your script, the user can trigger the countdown every time they click the button. However, the user should just initiate the countdown, and the countdown should then be triggered by itself in 1 second intervals.
To achieve that, you can use a flag to check whether the timer has been initiated or not and trigger the countdown on user click only the first time:
let timeLeft = 10;
function countdown() {
if (timeLeft > 0) {
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
setTimeout(countdown, 1000);
} else {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append('<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
}
timeLeft--;
};
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
}
}));
*I also took the liberty to change the trigger of the final message to be when the timeLeft reaches 0 instead of using 2 independent timers, but you can still use your way like this:
let timeLeft = 10;
function countdown() {
timeLeft--
$("#tmp_button-72286").text("Download will be ready in "+String(timeLeft)+"seconds");
if (timeLeft > 0) setTimeout(countdown, 1000);
};
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
let timerRunning = false;
$("#tmp_button-72286").bind("click", (function () {
if (!timerRunning) {
timerRunning = true;
countdown();
let timer_var = setInterval(timer, 10 * 1000);
}
}));
Try it. I just added variable done to check when function start and prevent from restart function.
let timeLeft = 10;
let done = false;
function countdown() {
timeLeft--;
$("#tmp_button-72286").text(
"Download will be ready in " + String(timeLeft) + "seconds",
);
if (timeLeft > 0) {
setTimeout(countdown, 1000);
}
}
function timer() {
$("#tmp_button-72286").text("");
$("#tmp_button-72286").append(
'<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>',
);
}
$("#tmp_button-72286").bind("click", function () {
if (!done) {
done = true;
countdown();
var timer_var = setInterval(timer, 10 * 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>
the code can be simplified like this, no need extra variable.
timeLeft = 10;
var tmpButton = $("#tmp_button-72286")
function countdown() {
tmpButton.text("Download will be ready in " + String(timeLeft) + " seconds");
if (timeLeft-- > 0)
setTimeout(countdown, 1000);
else
tmpButton.prop('outerHTML', '<a id="myLink" target="_blank" href="link"><button id="thor">Download Now</button></a>');
};
tmpButton.on("click", countdown);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="tmp_button-72286">Download Now</button>

Why two timers starts javascript issue, when timer start & I press some another timer at that time both timers are running

So here I create one contdown web application using HTML, CSS and JS and now I am stuck that how to reset the intervel time out function when click on some another button.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="timer">
<div class="timer__controls">
<button data-time="20" value="20" class="timer__button">20 Secs</button>
<button data-time="300" value="300" class="timer__button">Work 5</button>
<button data-time="900" value="900" class="timer__button">Quick 15</button>
<button data-time="1200" value="1200" class="timer__button">Snack 20</button>
<button data-time="3600" value="3600" class="timer__button">Lunch Break</button>
<form name="customForm" id="custom">
<input id="customMin" placeholder="Enter Minutes" >
</form>
</div>
<div class="display">
<h1 id="display__time-left">00:00</h1>
<p id="display__end-time">Be Back At 00.00</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Here in the script.js file as I mantioned , javascript uses the setTimeout feature of javascript to build one countdown web application and now when in a output browser I press Lunch time button it will show the timer for the next 1Hour and than it is stop in 00:00...
as I want if one timer is running and I press some another button or some custom input for taking seconds than at that time both timers are running.
So please provide the solution that what I have to do.
scripts.js
let allButtons = document.querySelectorAll(".timer__button");
let valueOfTime;
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener("click", function () {
valueOfTime = this.value;
BackAt();
});
}
setInterval(function () {
var minutes = Math.floor(valueOfTime / 60);
var seconds = valueOfTime % 60;
if (valueOfTime > 0) {
document.getElementById("display__time-left").innerHTML = minutes + ":" + seconds;
}
else{
document.getElementById("display__time-left").innerHTML = "00:00";
}
valueOfTime--;
}, 1000);
document.getElementById("customMin")
.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
let inputMin = document.getElementById("customMin").value *60;
inputBackAt(inputMin);
setInterval(function () {
var minutes = Math.floor((inputMin / 60));
var seconds = inputMin % 60;
if (inputMin > 0) {
document.getElementById("display__time-left").innerHTML =
minutes + ":" + seconds;
}
inputMin--;
}, 1000);
}
});
function BackAt() {
var minutes = Math.floor(valueOfTime / 60);
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let x = currentMin + minutes;
if (x > 59) {
let remainingMinutes = x-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
function inputBackAt(inputMin){
var minutes = Math.floor((inputMin/ 60));
let currentHours=new Date().getHours();
let currentMin= new Date().getMinutes();
let y = currentMin + minutes;
if (y> 59) {
let remainingMinutes = y-60;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
}
else{
let remainingMin =currentMin+minutes;
document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
}
}
when I click on one button and the timer is running , after some time when I press another button to start the new timer at that time both previous and current timer are running.
This defines a Timer class that instantiates an independent timer, then create multiple copies of it. The time for each timer as well as how long a "tick" can both be supplied as arguments to the constructor. Each time the timer ticks it can call the optional updateCallback to notify you.
The example starts three timers, one for three "minutes" (a minute it actually set to 3 seconds) that ticks every second, one for six "minutes" that ticks every 500 milliseconds and one for 15 "minutes" that ticks every 200 milliseconds.
Timer (seconds, period, update, reset)
seconds: How many seconds the timer should last
period: How long a "tick" is
update: [Optional] A callback that is called after every tick
reset: [Optional] A callback back that will be called when the timer ends (or if Timer.reset() is called)
let oneSecond = 500; // this should be 1000, set to 500 for the example
let oneMinute = 3; // this should be 60, set to 3 for the example
let sessionTime = 3;
function Timer(seconds, period, updateCallback, resetCallback) {
this.s = seconds;
this.p = period || oneSecond;
this.update = updateCallback || Function.prototype; // Use NOOP function as default
this.callback = resetCallback || Function.prototype; // Use NOOP function as default
this.reset = function() {
this.intervalId = clearInterval(this.intervalId)
this.callback()
}
this.start = function() { this.update(this.s); this.intervalId = setInterval(this.timer.bind(this), [ this.p ]) }
this.timer = function() { if (--this.s <= 0) this.reset(); this.update(this.s) }
}
function setTimeLeft(sec, id) {
document.getElementById(id || 'time-left').textContent = `${(''+ ~~(sec / oneMinute)).padStart(2, '0')}:${(''+ sec % oneMinute).padStart(2, '0')}`;
}
document.addEventListener("DOMContentLoaded", function() {
new Timer(sessionTime * oneMinute, 1000, setTimeLeft, () => console.log('check 1000ms')).start()
new Timer(6 * oneMinute, 500, (s) => { setTimeLeft(s, 'time-left2')}, () => console.log('check 500ms')).start()
new Timer(15 * oneMinute, 200, (s) => { setTimeLeft(s, 'time-left3')}, () => console.log('check 200ms')).start()
})
<span id='time-left'></span><br />
<span id='time-left2'></span><br />
<span id='time-left3'></span>

How to end my countdown timer when a button is clicked?

I'm trying to create a function that will end a countdown timer, or automatically make the minutes and seconds part of the countdown timer === 0; however, it seems that using clearInterval(time) doesn't seem to work! Could anyone point out how I might be able to achieve what I'm trying to do!
Note that I've made startingMinutes = 1 just for my ease.
Below is the countdown function and HTML:
// FUNCTION - countDown function that counts down from 8 minutes
const startingMinutes = 1;
let time = startingMinutes * 60;
function updateCountDown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
clearInterval(time);
})});
HTML:
//where the countdown timer is displayed
<div id="circle"><p id="countdown">8:00</p></div>
//Click the below button and the countdown timer will end (minutes === 0 and seconds === 0)
<button id="submit_button" type="submit">Click to Submit</button>
To use clearInterval you need to pass it the value returned by setInterval
I have an example below using your code, where I pass the value from "setInterval" which I call "interval" to a function "stop" which calls "clearInterval" to stop the timer, and runs the code you were running.
let isListening = true;
const recognition = { abort: () => console.log('aborted') };
function updateCountDown(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
const timer = document.getElementById("countdown");
timer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function start(time) {
const interval = setInterval(() => {
if (--time) updateCountDown(time);
else stop(interval);
}, 1000);
document.getElementById("submit_button")
.addEventListener("click", () => stop(interval))
}
function stop(interval) {
updateCountDown(0); // This line sets time to 0
clearInterval(interval);
foo()
}
// I assume you want this to happen when the timer runs down or the button is clicked
function foo() {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
start(8*60)
#tableStyle, #wordsIncluded, #show_header_one { display: none; }
<p id="tableStyle">Table Style</p>
<p id="wordsIncluded">Words Included</p>
<p id="show_header_one">Show Header One</p>
<div id="circle">
<p id="countdown">8:00</p>
</div>
<button id="submit_button" type="submit">Click to Submit</button>
const startingMinutes = 1;
let time = startingMinutes * 60;
var abort_count_down = true;
function updateCountDown() {
if (abort_count_down) {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
};
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
abort_count_down = false;
})});

Why is Javascript clearInterval not working on button click?

I have a timer program that counts down from 25:00 on "start" button click and is supposed to reset and clearInterval() on "reset" button click. When the timer reaches 0:00 the if statements all pass and resetTimer() is called which executes the clearInterval() which works in this instance. So in short: clearInterval() works when the if statements pass but not when I click the "reset" button. Can someone please explain to me why this is happening and offer a solution? Thank you!
//My Programs Code:
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
//**HERE resetTimer() is called and clearInterval works**
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
//**HERE resetTimer() is called but clearInterval doesn't work**
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//End Timer Widget
const timerMinute = document.querySelector("#minute");
const timerSeconds = document.querySelector("#seconds");
const timerStartBtn = document.querySelector("#timer-start");
document.querySelector("#timer-btns").addEventListener("click", timerStartReset);
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 0;
timerSeconds.innerHTML = 11;
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
console.log("reset");
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 10;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
}
//End Timer Widget
<!-- Timer -->
<div>
<span id="minute">0</span>
<span>:</span>
<span id="seconds">11</span>
</div>
<div id="timer-btns">
<button id="timer-start">Start</button>
<button id="timer-reset">Reset</button>
</div>
<!-- End Timer -->
The variables minutesInterval and secondsInterval are local to this function. So every time you call the function, it starts new timers and creates new variables. When the code calls resetTimer(), it's only resetting the timer started by that invocation of timerStartReset, not the previous ones.
It works when the timer runs out, because the countdown code is in the same scope. But when you click the Reset button, that function is a new scope and can't access the variables from when the Start button was clicked.
The timer variables should be global variables that can be accessed from any invocation. And then there's no reason to use the same function for both buttons.
var minutesInterval;
var secondsInterval;
timerStartBtn.addEventListener('click', timerStart);
timerResetBtn.addEventListener('click', resetTimer);
function timerStart() {
resetTimer();
var minutes;
var seconds;
//decrease minutes html every minute
minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
startTimer();
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//End Timer Widget

How to stop and reset a countdown timer?

I need to display a countdown timer starting with 10. Whenever I click any button while it is running, the counter will reset again. The below function is working well but whenever I am clicking the button in the midst of the counting, the timer counter is fast forwarding and showing too fast.
var timeleft = 10;
var downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);
function fn_start() {
var timeleft = 10;
var downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>
You need to clear the interval every time you call your function.
<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
var downloadTimer; // global var
function fn_start() {
var timeleft = 10;
clearInterval(downloadTimer);
downloadTimer = setInterval(function() {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
}, 1000);
}
// If you don't need to show the timer first, comment this line
fn_start();
</script>

Categories

Resources