Is my code wrong or is there a more effective way to do what i posted? I don't know how to do it better.
In the code there is a timer that restarts every time when it reaches 0.
A dynamic reading on the div.counter with the condition 'if the counter reaches 0s it must also press the button autonomously.
<body>
<h1>Callback</h1>
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
</body>
let timer = document.querySelector("#timer");
let text = document.getElementById('text')
let btn = document.getElementById('btn')
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
var myTimer = setInterval(myFn, 1000);
setInterval(() => {
time = timer.textContent
console.log(time)
if (time === '0') {
btn.click()
}
}, 1000);
btn.onclick = function () {
text.innerHTML += 'clicked' + '<br>'
}
Related
My countdown timer does not work. I ideally I want it to start when the start buttons is clicked, am I missing something? I've done the event listener on click to the startButton variable, which has a document.getElementById("start-button") to the HTML. I'm not sure why it isn't working.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown () {
setInterval(function(){
if (timer <= 0) {
clearInterval(timer = 0)
}
countdownDisplay.innerHTML = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button" href="quiz.html">Start Game - Kick Off</a>
</div>
Do not use a <a> tag with href attribute since your page will reload to the new url path. Instead just use a button:
As #Scott Marcus said, do not use .innerHTML when the text is not HTML as .innerHTML has security and performance implications. Use .textContent instead.
As #Dave Newton said, the argument to clearInterval should be an interval reference returned by setInterval. So relate the interval to a variable.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown () {
let mytimer = setInterval(function(){
if (timer <= 0) {
clearInterval(mytimer)
}
countdownDisplay.textContent = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<button type="button" class="button" id="start-button">Start Game - Kick Off</button>
<br>
<label id="countdown-timer">Start number</label>
</div>
Remove the href attribute from the anchor - it's causing you to leave/reload the page.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60;
let startGame = document.getElementsByClassName("button");
let t;
function countDown() {
t = setInterval(function() {
if (timer <= 0) {
clearInterval(t)
}
countdownDisplay.innerHTML = timer
timer -= 1
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button">Start Game - Kick Off</a>
</div>
seems to be ok to me. I adjusted the html to remove link, add element to display countdown and added log.
I removed link because if you click on link you are navigating away from page.
also you should learn how the snippets work on stack overflow, you will get more answers.
let countdownDisplay = document.getElementById("countdown-timer");
let startButton = document.getElementById("start-button");
let timer = 60; //document.getElementsByClassName("countdown");
let startGame = document.getElementsByClassName("button");
function countDown() {
setInterval(function() {
if (timer <= 0) {
clearInterval(timer = 0);
}
//countdownDisplay.innerHTML = timer;
timer -= 1;
countdownDisplay.innerHTML = timer;
console.log(timer);
}, 1000)
}
startButton.addEventListener('click', countDown)
<div id="start-game">
<a class="button" id="start-button">Start Game - Kick Off</a>
</div>
<div id="countdown-timer" />
This question already has an answer here:
want the counter to continue to count? [duplicate]
(1 answer)
Closed 2 years ago.
What do I need to add to make the button turn off if pressed 10 times in less than 1 minute but keep counting if not pressed in 1 minute?
function buttonClicked() {
if (totalCount + accCounter > 9) {
document.getElementById("btn").disabled = true;
}
}
document.getElementById('btn').onclick = function() {
upClickCounter();
buttonClicked()
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
let accCounter = 0;
let totalCount = 0;
<button id="btn">Click me</button>
<div id="clicker">
<span></span>
</div>
<div id="totalCounter"></div>
setTimeout(countOver, 10000); //set for 10 seconds
function countOver(){
document.getElementById('btn').disabled=true
}
function buttonClicked() {
if (totalCount + accCounter > 9) {
document.getElementById("btn").disabled = true;
}
}
document.getElementById('btn').onclick = function() {
upClickCounter();
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
let accCounter = 0;
let totalCount = 0;
<button id="btn">Click me</button>
<div id="clicker">
<span></span>
</div>
<div id="totalCounter"></div>
You need a setTimeout. It takes in a callback function and a timer in milliseconds. I updated upClickCounter with a line that disables the button, then a setTimeout that will re-enable the button after 1 minute (60,000 milliseconds).
EDIT:
I think I understand what you want, and can only wonder why, but this should do what you are describing.
let accCounter = 0;
let totalCount = 0;
let lessThanOneMinute = true;
function upClickCounter(event) {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
// If the click count is greater or equal to 10 and the lessThanOneMinute is still true, disable the button
if (accCounter >= 10 && lessThanOneMinute) { event.target.disabled = true; }
}
document.getElementById('btn').onclick = upClickCounter;
setTimeout(() => { lessThanOneMinute = false }, 60000); // the lessThanOneMinute variable will become false in one minute
I have a button that disappears by a function after one second.
if I click on the button, I want the function will reset and I will get one another second to click. And-I want the button will disappeared if I did not click this second.
(if I click in a second, the button doesn't disappeared, if I miss one second, it is disappeared, but if I click, I'll get another second, and so on...)
This is my code:
HTML:
<button id="btn">click
</button>
JavaScript:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
setTimeout(function click() {
btn.style.display = ('none');
}, 1000);
That code doesn't work.
I am an absolute beginner, so any feedback will help me.
If my question is not understood, please write to me in the comments or edit the question.
This is my suggestion:
var c = 10;
var timer;
clock();
function clock() {
timer = setInterval(countdown, 1000);
}
function countdown() {
counter.innerHTML = --c;
if (c === 0) {
btn.style.display = 'none';
clearInterval(timer);
}
}
btn.onclick = function() {
clearInterval(timer);
c = 10;
counter.innerHTML = c;
clock();
};
<button id="btn">Click me before it's too late (<span id="counter">10</span>)</button>
Change your javascript to the following:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
function click() {
setTimeout(function() {
btn.style.display = 'none';
}, 1000);
}
Click was not defined properly :)
You should try jQuery, it'll make your learning a lot easier!
Also press f12 on Google Chrome to show developer console, errors will show up there.
You need to apply the display:none inside setTimeout. Here is an example.
let btn = document.querySelector('#btn');
let time = document.querySelector('#time');
const timeLimit = 10;
let timeoutId, intervalId;
time.innerText = timeLimit;
let startTime;
window.onload = () => {
startTime = Date.now();
startTimer();
removeButton();
}
btn.addEventListener('click', stop);
function stop() {
intervalId && clearInterval(intervalId);
timeoutId && clearTimeout(timeoutId);
}
function startTimer() {
let count = 1;
intervalId = setInterval(() => {
if(count === 10) clearInterval(intervalId);
time.innerText = timeLimit - count;
count++;
}, 1000);
}
function removeButton() {
timeoutId = setTimeout(() => {
btn.style.display = 'none';
}, timeLimit*1000);
}
<button id="btn">Click me. I am disappearing ⏳ <span id="time"></span></button>
How can I clean interval+message and replace those with a link.
Below code is opening a link after 10 seconds in new window. When I get back to that page, message showing You will redirect in 0 seconds
What I want is, after 10 seconds (after opening link in new tab) the counter and message will replace with a new message and link. i.e. If you are not redirected to the link Click Here to go to the link.
var count = 10;
var counter;
function start(){
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
return;
}
}
window.addEventListener("load", start, false);
<br>You will redirect in <span id="displaySeconds">10</span> seconds.<br />
You can create a separate div with the text when the user is not redirected with the display property set to none (display: none). When the timer expires, you can hide the original text and show the alternative version.
There is a working jsfiddle below. I modified the counter to 4 seconds not to wait too much, you can adjust it how you want.
var count = 4;
var counter;
function start() {
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
let originalText = document.getElementById("original");
let noRedirectText = document.getElementById("noredirect");
originalText.style.display = "none";
noRedirectText.style.display = "block";
}
}
window.addEventListener("load", start, false);
<div>
<div id="original">
You will be redirected in <span id="displaySeconds">4</span> seconds.
</div>
<div style="display: none" id="noredirect">
If you are not redirected click here to go to the link.
</div>
</div>
Cheers!
Just add code to the interval function that hides the first message and shows the other.
var count = 5;
var output = document.getElementById("displaySeconds");
var counter = null;
function timer() {
output.textContent = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
// Hide the first message and show the second:
document.querySelector(".redirect1").classList.add("hidden");
document.querySelector(".redirect2").classList.remove("hidden");
}
}
addEventListener("load", function(){
couner = setInterval(timer, 1000);
});
.hidden { display:none; }
<div class="redirect1">You will redirect in <span id="displaySeconds">5</span> seconds.</div>
<!-- The following is initially hidden because of the CSS class -->
<div class="redirect2 hidden">If you aren't redirected, click here</div>
This function replaces the current text with your required text if the redirect was not able to take place.
var count = 10;
var counter = setInterval(timer, 1000);
var output = document.getElementById("displaySeconds");
var container = document.getElementById("container");
function timer() {
count--;
if (count === 0) {
stopTimer();
}
output.innerHTML = count;
};
function stopTimer() {
clearInterval(counter);
window.open("https://www.google.com");
container.innerHTML = ' If you are not redirected to the link Click Here to go to the link.';
}
<div id="container">
You will redirect in <span id="displaySeconds">10</span> seconds.
</div>
How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>