Onclick reset setInterval - javascript

<!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

Related

Is these a way to add 1 and then after one second than add 2 and than 3 etc

What I am looking for would essentially be a "++" to a "++" command using native java script. The program simply runs an animation for a given number in which the idea of the animatio is that it adds 1 after one second, two after two seconds and keeps going in the same fashion until the animation is stopped.
var counter = 10;
var animationOn = false;
var counterAnimation;
var plusOne;
function updateCounter() {
//update the counter value
var plusOne = counter++;
for (var i = 1; i = < 100000000;) {
}
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
}
function startCounterAnimation() {
if (animationOn == false) {
animationOn == true;
counterAnimation = setInterval(updateCounter, 1000);
}
}
function stopCounterAnimation() {
if (animationOn == true) {
animationOn == false;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You don't need the for loop.
You should assign to the global plusOne variable, not declare a local variable in the function.
You should add counter++ to it, not assign that directly.
Initialize plusOne from the number already in the output span.
Since your time intervals change between each update, you can't use setInterval(). Use setTimeout() to make a different timeout each time.
Use =, not ==, to assign to the animationOn variable.
var counter;
var animationOn = false;
var counterAnimation;
var plusOne = parseInt(document.getElementById("counterHolder").innerHTML);
function updateCounter() {
//update the counter value
plusOne += counter++;
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
counterAnimation = setTimeout(updateCounter, counter * 1000);
}
function startCounterAnimation() {
if (!animationOn) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateCounter, 1000 * counter);
}
}
function stopCounterAnimation() {
if (animationOn) {
animationOn = false;
clearTimeout(counterAnimation);
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You can´t define var onePlus in two places, instead define it once and assign a value, var is wide scoped
Also add whatever logic you need in the for loop and put the onePlus ++ and counter as parts of the for loop
As it is now you are expecting to use the counter both outside the for loop and as the for loop middle part, which seems reduntant
Try something like(leaving the variable names as are):
var counter = 1000
for (var plusOne = 1; plusOne < counter; plusOne++) {
//Your logic in here
await sleep(1000);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Javascript counter speeds up after the second button click

I have a counter which is activated once startnew button is clicked:
<button id="startnew" onclick="counter()">Start new Game</button>
var i = 0;
function counter() {
var execution = setInterval(function(){
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
The problem comes when I click on the startnew button for the second time, where counter starts to speed up as an inner variable stays the same.
I have tried adding additional if clauses in different parts of a code which would check if a button was already clicked but had no success so far.
How can I reset an inner variable once the same button was clicked for a second time?
You are creating a new setInterval everytime you click the button.
Call clearInterval(execution) before setInterval and make var execution global. Also Declare your variable i inside the function counter.
var execution;
function counter() {
var i = 0;
clearInterval(execution);
execution = setInterval(function() {
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<br>
<span id="timer"></span>
I hope i understood your Requirement...
Make the variable execution in Global Scope
var i = 0;
var execution;
function counter() {
if (i === 0) {
execution = setInterval(function() {
active()
}, 1000);
} else {
clearInterval(execution);
i = 0;
document.getElementById("timer").innerHTML = '';
}
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<span id='timer'></span>

timer using javascript

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.

Categories