Using Onclick to call a nested function - javascript

I want to implement a basic timer program that starts a 15 second timer on start button and stops on stop button
Here is what I have done so far
JS
var timeleft = 15;
function timer(){
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
function timerstop(){
clearInterval(downloadTimer);
}
}
HTML
<div id="countdown"></div>
<button onclick="timer();">start</button>
<button onclick="timerstop();">stop</button>
The reason I had to use the nested function approach was to access the variable downloadtimer, the start button works as expected but on clicking the stop button I get the following error
Uncaught ReferenceError: timerstop is not defined
I would like to know if is this is a programming error or should I change my approach
Thanks in Advance

Move downloadTimer outside.
var timeleft = 15;
var downloadTimer;
function timer() {
downloadTimer = setInterval(function () {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
}
function timerstop() {
clearInterval(downloadTimer);
}

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>

How to run countdown if user active on my website?

I used this code to count down when users were on my site. However it still works (countdown) when I work on another browser tab.
Please help me
<style>
#permalink{display:none}
</style>
<script>
if (document.hasFocus())
{
var timeleft = 10;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Done";
document.getElementById("permalink").style.display = "block";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
}
</script>
<div id="countdown"></div>
<div class="ebook-buttons">
<span id="download-button"><a id="permalink" href="/download/file.zip" rel="nofollow">Download</a></span>
</div>
You can use focus and blue event to identify that either user is on current tab or not. So check this solution:
<style>
#permalink{display:none}
</style>
<script>
var downloadTimer;
var timeleft = 500;
function startTimer() {
downloadTimer = setInterval(function () {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Done";
document.getElementById("permalink").style.display = "block";
} else {
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
}
timeleft -= 1;
}, 1000);
}
function stoptimer() {
window.clearInterval(downloadTimer);
}
window.addEventListener('focus', startTimer);
window.addEventListener('blur', stoptimer);
</script>
<div id="countdown"></div>
<div class="ebook-buttons">
<span id="download-button"><a id="permalink" href="/download/file.zip" rel="nofollow">Download</a></span>
</div>

How do I automatically Start the timer when I reload this Page?

<p id="countdown"></p>
<div id="startButtons">
<button onclick="sample()" id="gameStart" class="gameStart">LETS GO!</button>
<script>
var timeleft = 90;
window.onload = timedText;
function sample() {
document.getElementById('paragraph').innerHTML = "<style>.paragraph(visibility:collapse);";
document.getElementById('gameStart').innerHTML = "<style>.gameStart(visibility:collapse);";
var downloadTimer = setInterval(function
function1() {
document.getElementById("countdown").innerHTML = timeleft + "&nbsp" + "seconds left";
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "The time has ended!";
window.open("index2.1.html");
}
}, 1000);
console.log(countdown)
}
</script>
I making this game of words and I don't really get how to start the timer when I reload the page, I want the timer to start by itself, So if I click Enter on the home page and reach this page the timer should start by itself..., and when the timer gets finished another window should open that is the 2.1 index.html
Thank you
Rather than wrapping your JavaScript loop up in a function that needs to be called on page load, just run the JavaScript directly (without placing in a function) and the page will run it as soon as it reads/loads it.
<p id="countdown">Countdown Beginning</p>
<script>
var timeleft = 90;
var downloadTimer = setInterval(function () {
document.getElementById("countdown").innerHTML = `${timeleft} seconds left`;
timeleft -= 1;
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "The time has ended!";
}
}, 1000);
</script>

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>

JavaScript timer for a quiz

I am making a quiz game for a project in HTML and JavaScript. On every question, the player has 15 seconds to answer. I managed to do it like this:
<body onload="setTimeout(Timer,15000)">
and then in Js:
function Timer()
{
alert("You are out of time!");
}
However, I want to be able to display how much time the player has left in a <p> tag. How could I do that?
<div id="count">Start</div>
var count = 15;
var interval = setInterval(function(){
document.getElementById('count').innerHTML=count;
count--;
if (count === 0){
clearInterval(interval);
document.getElementById('count').innerHTML='Done';
// or...
alert("You're out of time!");
}
}, 1000);
Here's a basic example of a countdown timer
var count = 15;
var timer = setInterval(function() {
console.log(count);
count--;
if(count === 0) {
stopInterval()
}
}, 1000);
var stopInterval = function() {
console.log('time is up!');
clearInterval(timer);
}
Repl: https://repl.it/I2C6
Initialize the variable 'sec' with timeout time in seconds.
Call setInterval() which has 2 parameters, 1st is the method name and 2nd parameter is interval between invoking the method mentioned in 1st parameter.
var sec = 15;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById('timer').innerHTML = sec + "sec left";
sec--;
if (sec == -1) {
clearInterval(time);
alert("Time out!! :(");
}
}
Time : <span id="timer"></span>

Categories

Resources