Reset function by button - javascript

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>

Related

how to improve the code with the constructor maybe?

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>'
}

Why won't my timer function in JS start countdown?

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" />

Wait until user is finished clicking | JavaScript

I want to count the clicks while the user keeps clicking.
After about half a second when there are no more clicks on a specific button, the function should return the accumulated clicks.
I've tried it with this but, doesn't really work:
HTML:
Next
JavaScipt:
cntNav(element){
let btn = element.target
let cnt = 0
let t = setTimeout(function(){
console.log(cnt)
}, 1000)
btn.addEventListener("click", function(){
cnt++
})
}
Console Output (after 5x clicking):
4
3
2
1
0
You could create a timeout to delay returning the clicks.
const main = () => {
new Clicker('#click-me', {
timeout: 500,
callback: (clicks) => console.log(`Clicks: ${clicks}`)
});
};
class Clicker {
constructor(selector, options) {
this.reference = typeof selector === 'string' ?
document.querySelector(selector) : selector;
let opts = Object.assign({}, Clicker.defaultOptions, options);
this.timeout = opts.timeout;
this.callback = opts.callback;
this.initialize();
}
initialize() {
this.__clickCount = 0;
this.__activeId = null;
this.reference.addEventListener('click', e => this.handleClick())
}
handleClick() {
this.__clickCount += 1;
clearTimeout(this.__activeId); // Reset the timeout
this.__activeId = setTimeout(() => {
this.callback(this.__clickCount);
this.__clickCount = 0; // Reset clicks
}, this.timeout);
}
}
Clicker.defaultOptions = {
timeout: 1000
};
main();
<button id="click-me">Click me!</button>
HTML:
<button onclick="cntNav();">Click Me!</button>
JS:
var cnt = 0;
var myTimeOut;
cntNav = function(){
clearTimeout(myTimeOut);
myTimeOut = setTimeout(function(){
console.log(cnt);cnt=0;
}, 1000)
cnt++;
}
This removes the timeout whenever someone clicks, so if someone clicks before the timeout has called, then it will be cleared. It will only call when someone leaves enough time in-between clicks. This then also sets the count back to zero.

How do I repeat a function while holding the mouse down with JavaScript?

Trying to run a function repeatedly while holding down the left mouse button with this code but it's not working. Any ideas to correct it will be appreciated.
var timer = 0;
document.getElementById('myButton').onmousedown = function() {
while (this.event) {
timer = setInterval(function() {c_3()}, 100);
}
clearInterval(timer);
}
you can solve this in multi way
check this https://codepen.io/hamidrezanikoonia/pen/bvarGL?editors=0011
var interval_;
document.getElementById('ele').onmousedown = function() {
interval_ = setInterval(function(){ console.log("Hello"); }, 300);;
}
document.getElementById('ele').onmouseup = function() {
clearInterval(interval_); wdsd
}
i use setInterval for doing this
Try adding mouseover and mouseup listeners when the button gets pressed down while over the button:
const button = document.querySelector('div');
button.addEventListener('mousedown', () => {
let mouseIsDown = true;
document.body.addEventListener('mouseup', () => clearTimeout(intervalLog));
document.body.addEventListener('mouseover', (e) => {
if (e.target !== button) clearTimeout(intervalLog);
});
const intervalLog = setInterval(() => console.log('mouse is down over button.'), 300);
});
<div>
button
</div>
<div>
div
</div>

Stopwatch in JavaScript

Before marking the question duplicate, I want to tell that I have been through all the stopwatch and JavaScript searches but as I am new to the JavaScript, so I can not come to the possible solution myself and I need the help from you guys.
What I want to achieve is to start and stop the watch with the same button. I can stop the watch but can not start again, can't figure out why.
Have a look at the following script and correct me.
var startTimer = setInterval(function(){myTimer()}, 1000);
function myTimer(){
var current = new Date();
document.getElementById("timer").innerHTML = current.toLocaleTimeString();
}
function start(st){
// Problem is in this statement
// How can I call the global function variable again that's startTimer
window[st]();
var elem = document.getElementById("myButton");
elem.innerHTML = "Stop";
elem.addEventListener("click", stop);
}
function stop(){
clearInterval(startTimer);
var elem = document.getElementById("myButton");
elem.innerHTML = "Start";
elem.addEventListener("click", start(startTimer));
}
<p id="timer"></p>
<button id="myButton" onclick="stop(startTimer)">Stop</button>
You want a single method to take care of the start/stop:
var startTimer = setInterval(myTimer, 1000),
timerElement = document.getElementById("timer"),
buttonElement = document.getElementById("myButton");
function myTimer(){
var current = new Date();
timerElement.innerHTML = current.toLocaleTimeString();
}
function toggle(){
if (startTimer) {
clearInterval(startTimer);
startTimer = null;
buttonElement.innerHTML = "Start";
} else {
buttonElement.innerHTML = "Stop";
startTimer = setInterval(myTimer, 1000);
}
}
<p id="timer"></p>
<button id="myButton" onclick="toggle()">Stop</button>
Why clearing your interval?
catch-up where the interval left.
var timer = document.getElementById("timer"),
paused = 0;
setInterval(function(){
if(!paused) timer.innerHTML = new Date().toLocaleTimeString();
}, 1000);
document.getElementById("myButton").addEventListener("click", function(){
this.innerHTML = (paused ^= 1) ? "Start" : "Stop";
});
<p id="timer"></p>
<button id="myButton">Stop</button>
P.S: Always cache elements you plan to reuse, specially if inside an interval fn.
(paused ^= 1) is used to toggle ones and zeroes 1,0,1,0,1... used than as boolean.

Categories

Resources