Repeating a setInterval - javascript

I'm currently using a setInterval function in JavaScript for an HTML page. It has a button that allows me to start a countdown from 10 to 0 with a 1 second interval, and every time I press the button the countdown is supposed to reset. However, after the first button press the next countdown messes up the interval badly.
var count;
function countdown() {
count = 10;
var repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
<html>
<head>
<title>Page 4</title>
</head>
<body>
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
</body>
</html>

You could use a global variable repeat and reset if set when countdown is invoked.
var count,
repeat;
function countdown(){
count = 10;
if (repeat) {
clearInterval(repeat);
}
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
<button style=" display: inline-block; " onclick ="countdown()" >Start Count Down</button>
<div style="display: inline-block;" id="number"></div>

You problem is the repeat variable, it's defined and accessible only inside countdown.
You could just make it global as well, and then you'd have to clear previous intervals when clicking the button again
var count, repeat;
function countdown() {
clearInterval(repeat);
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count;
count--;
} else {
clearInterval(repeat);
}
}
FIDDLE

put your repeat outside so the function reduce can access it
var count;
var repeat = null;
function countdown(){
count = 10;
repeat = setInterval(reduce, 1000);
}
function reduce() {
if(count > 0)
{document.getElementById('number').innerHTML = count;
count--;}
else
{clearInterval(repeat);}
}

You can also use this to stop interval;
clearInterval(this)
var count;
function countdown() {
count = 10;
var repeat = setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count--;
} else {
clearInterval(this);
}
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
This will solve your issue but will raise another issue. If you click multiple times, multiple events will be registered. For this, you should either disable button or define repeat in parent scope.
var count, repeat;
function countdown() {
count = 10;
repeat = repeat || setInterval(reduce, 1000);
}
function reduce() {
if (count > 0) {
document.getElementById('number').innerHTML = count--;
} else {
clearInterval(this);
}
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>
You will notice a simple trick:
repeat = repeat || setInterval(reduce, 1000);
This will ensure multiple intervals are not registered.

Related

i am not able to add color to my counter project

i am creating a counter project which increase reset or decreases the count when respective button is clicked and colour of count also changes for postive negative and zero value of count but i am unable to change colour of count if it is positive, negative, zero but my code just performs when count is zero.
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
<link rel="stylesheet" type="text/css" href="./counter.css">
</head>
<body>
<h1>Counter<h1>
<h1 id="counter">0</h1>
<div>
> <ul>
<li id="decrease"><button>DECREASE</button></li>
<li id="reset"><button>RESET</button></li>
<li id="increase"><button>INCREASE</button></li>
</ul>
</div>
<script src="counter.js">
</script>
</body>
</html
const decrease = document.getElementById("decrease");
const increase = document.getElementById("increase");
const reset = document.getElementById("reset");
var counter = document.getElementById("counter");
var count = 0;
decrease.addEventListener("click", function(){
count -= 1;
counter.textContent = count;
});
increase.addEventListener("click", function(){
count += 1;
counter.textContent = count;
});
reset.addEventListener("click", function(){
count = 0;
counter.textContent = count ;
});
counter.style.color = colour();
function colour(){
if (count === 0){
return "blue";
}
if(count > 0){
return "green";
}
if(count < 0){
return "black";
}
}
You have an issues in the way you are trying to update color that is the reason it is not being updated. Instead of calling function on every click, you are just running it single time and hence the issue. You should create a function to update color and call it after updating counter in all 3 click handlers.
let count = 0;
const elemCounter = document.getElementById("counter");
function increase() {
count++;
updateCount();
}
function decrease() {
count--;
updateCount();
}
function reset() {
count = 0;
updateCount();
}
function updateCount() {
elemCounter.innerText = count;
updateColor();
}
function updateColor() {
let color = "blue";
if (count > 0) {
color = "green";
} else if (count < 0) {
color = "red";
}
elemCounter.style.color = color;
}
#counter {
padding: 5px;
margin-bottom: 5px;
height: 25px;
}
<div id="counter"></div>
<button onclick="increase()">Increase</button> <br />
<button onclick="decrease()">Decrease</button> <br />
<button onclick="reset()">Reset</button>

HTML: How to get multiple timers to combine

I am building a timer based on user inputs. Below is how to code should work:
User inputs:
Time on: 30s
Time off: 10s
Number of sets: 4
Number of exercises per set: 5
Rest in between sets: 30s
With the above user inputs the timer will do this:
Hopefully that makes sense on what It is supposed to do. I am currently trying to implement the rest in between sets. Does anyone know how I could make that happen with how my code currently is? Also totalTime already includes the amount of time the rest in between sets would add on if that helps.
var numsets = document.getElementById("userInput1");
var numex = document.getElementById("userInput2");
var numwork = document.getElementById("userInput3");
var numrest = document.getElementById("userInput4");
var numrestafterset = document.getElementById("userInput5");
var sets;
var OGtimeon;
var OGtimeoff;
var totalTime;
var timeRemaining;
var hasBeenStarted = false; // Boolean value to test what time to use
var isTimeON = true;
var timeon;
var timeoff;
var timeonRemaining;
var timeoffRemaining;
var setsRemaining;
var OGsets;
var Prepare;
var OGExPS;
var OGTOASets;
var ExercisePS;
var RestAfterS;
var Intervals
var j = 0;
var ExercisesRemaining;
var RestRemaining;
// function sleep(milliseconds) { //function I found online to create a sleep function
// const date = Date.now();
// let currentDate = null;
// do {
// currentDate = Date.now();
// } while (currentDate - date < milliseconds);
// }
// function updateRest() {
// if (RestAfterS > 0) {
// interval3 = setInterval(RestCount, 1000);
// }
// else {
// startTime();
// }
// function RestCount() {
// while (RestAfterS != 0) {
// RestAfterS--;
// }
// j = 0;
// }
function updatePrep() {
if (hasBeenStarted == false) {
Prepare = 5;
interval2 = setInterval(PrepCount, 1000);
}
else {
startTime();
}
}
function PrepCount() {
let seconds = parseFloat(Prepare) % 60;
if (Prepare == 0) {
clearInterval(interval2);
startTime();
}
else {
PWR.innerHTML = "Get Ready!";
textarea.innerHTML = Prepare;
console.log(Prepare);
Prepare--;
}
}
function startTime() {
// Set values in code
OGsets = numsets.value;
OGtimeon = numwork.value;
OGtimeoff = numrest.value;
OGTOASets = numrestafterset.value;
OGExPS = numex.value;
timeon = (hasBeenStarted)? timeonRemaining : OGtimeon;
timeoff = (hasBeenStarted)? timeoffRemaining : OGtimeoff;
sets = (hasBeenStarted)? setsRemaining : OGsets;
ExercisePS = (hasBeenStarted)? ExercisesRemaining : OGExPS;
RestAfterS = (hasBeenStarted)? RestRemaining : OGTOASets;
// How much time on timer
// Var = (expression)? true : false this is basically an if statement
totalTime = (hasBeenStarted)? timeRemaining : ((parseFloat(OGtimeon)*parseFloat(sets)*parseFloat(ExercisePS))+(parseFloat(OGTOASets)*(parseFloat(sets)-1))+(parseFloat(OGtimeoff)*(parseFloat(sets)*(parseFloat(ExercisePS)-1))));
Intervals = ((parseFloat(sets)*parseFloat(ExercisePS))+((parseFloat(sets)-1))+((parseFloat(sets)*(parseFloat(ExercisePS)-1))));
hasBeenStarted = true;
// Start timer
interval = setInterval(updateCountdown, 1000);
}
function updateCountdown() {
IntervalsLeft.innerHTML = Intervals;
setsLeft.innerHTML = sets;
var minutes= Math.floor (parseFloat(totalTime) / 60);
var seconds = parseFloat(totalTime) % 60;
if (seconds < 10) {
textareaRemaining.innerHTML = minutes + ":0" + seconds;
} else {
textareaRemaining.innerHTML = minutes + ":" + seconds;
}
// Update TimeON / Time OFF
if(isTimeON){
PWR.innerHTML = "Work!";
textarea.innerHTML = timeon;
timeon--;
if(timeon == 0){
isTimeON = false;
timeon = OGtimeon;
Intervals--;
IntervalsLeft.innerHTML = Intervals;
}
}
//BELOW IS THE AREA I AM STUCK ON
else{
textarea.innerHTML = timeoff;
timeoff--;
PWR.innerHTML = "Rest!";
if(timeoff == 0){
isTimeON = true;
timeoff = OGtimeoff;
j++;
Intervals--;
IntervalsLeft.innerHTML = Intervals;
if (j == OGExPS) {
sets--;
//updateRest();
j = 0;
}
}
}
if( totalTime == 0 ){
clearTimeout(interval);
hasBeenStarted = false;
console.log(sets);
sets--;
setsLeft.innerHTML = sets;
PWR.innerHTML = "OMG YOU'RE DONE";
}
totalTime--;
}
function updateRest() {
if (RestAfterS > 0) {
interval3 = setInterval(RestCount, 5000);
}
else {
startTime();
}
}
function RestCount() {
while (RestAfterS != 0) {
RestAfterS--;
PWR.innerHTML = "Set Rest!";
textarea.innerHTML = RestAfterS;
}
j = 0;
clearInterval(interval3);
}
function stop(){
timeRemaining = totalTime;
timeonRemaining = timeon;
timeoffRemaining = timeoff;
RestRemaining = RestAfterS;
ExercisesRemaining = OGExPS;
setsRemaining = sets;
clearTimeout(interval);
// document.getElementById("Counter").innerHTML = j;
}
p {
display: inline-flex;
align-items: center;
}
label {
float: left;
display: block;
}
#userInput1 {
display: flex;
margin-bottom: 10px;
}
#userInput2 {
display: flex;
margin-bottom: 10px;
}
#userInput3 {
display: flex;
margin-bottom: 10px;
}
#userInput4 {
display: flex;
margin-bottom: 10px;
}
#userInput5 {
display: flex;
margin-bottom: 10px;
}
#Prepare {
display: flex;
margin-bottom: 10px;
}
#sets {
display: flex;
margin-bottom: 10px;
}
#timeon {
display: flex;
margin-bottom: 10px;
}
#timeoff {
display: flex;
margin-bottom: 10px;
}
#TotalTime {
display: flex;
margin-bottom: 10px;
}
#Counter {
display: flex;
margin-bottom: 10px;
}
input {
height: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="Countdown From Scratch.css" />
</head>
<script src="Countdown From Scratch.js" defer></script>
<body>
<label>Number of Sets </label>
<input id="userInput1" type="numsets" value = "0"/>
<label>Number of Exercises per Set </label>
<input id="userInput2" type="numex" value = "0"/>
<label>Time to Work </label>
<input id="userInput3" type="numwork" value = "0"/>
<label>Time to Rest </label>
<input id="userInput4" type="numrest" value = "0"/>
<label>Time Inbetween Sets </label>
<input id="userInput5" type="numrestafterset" value = "0"/>
<p id="Prepare"></p>
<div id="sets"> </div>
<div id="timeon"> </div>
<div id="timeoff"> </div>
<div id="TotalTime"> </div>
<textarea id="textarea" placeholder="00:00"></textarea>
<textarea id="PWR" placeholder="Hello!"></textarea>
<textarea id="textareaRemaining" placeholder="00:00"></textarea>
<textarea id="setsLeft" placeholder="00"></textarea>
<textarea id="IntervalsLeft" placeholder="00"></textarea>
<button onclick="updatePrep()">Start time</button>
<button onclick="stop()">Stop time</button>
</body>
</html>
I think I have a rough idea of what you are trying to accomplish here, but please let me know if I have misinterpreted anything.
Suppose you want to execute a sequence of effects with some duration in between them. To keep the example small, we'll use console.log as a stand-in for any effect you'd want to execute (for instance, setting the innerHTML of a DOM element).
As a first example, here we wait for 1 second, display "Hello", then wait for 1.5 seconds and display "There":
setTimeout(() => {
console.log('Hello');
setTimeout(() => {
console.log('There');
}, 1500);
}, 1000);
We can clarify this by describing the common parts as a function:
function logAfter(message, delay, callback) {
setTimeout(() => {
console.log(message);
if (callback) callback();
}, delay);
}
Then our example can be written as:
logAfter('Hello', 1000, () => {
logAfter('There', 1500);
});
As another example that is perhaps more relevant to your project, here is how we can create a "loop" that performs an effect multiple times:
function logNAfter(message, times, delay, callback) {
if (times === 0 && callback) {
callback();
}
else {
setTimeout(() => {
console.log(message);
logNAfter(message, times-1, delay, callback);
}, delay);
}
}
We could use this to display "Hi There!" 3 times, each separated by half a second, and then display "Goodbye!" once, 2 seconds later:
logNAfter('Hi There!', 3, 500, () => {
logAfter('Goodbye!', 2000);
});
In theory, you could create an arbitrarily-long sequence of appropriately spaced effects in this way. However, I should also mention that many would prefer to describe these effects as Promises instead:
function logAfter(message, delay) {
return new Promise(resolve => {
setTimeout(() => {
console.log(message);
resolve();
}, delay);
});
}
function logNAfter(message, times, delay) {
if (times === 0) {
return Promise.resolve();
} else {
return logAfter(message, delay)
.then(() => logNAfter(message, times-1, delay));
}
}
The original examples then become:
logAfter('Hello', 1000)
.then(() => logAfter('There', 1500));
logNAfter('Hi There!', 3, 500)
.then(() => logAfter('Goodbye!', 2000));
This is arguably only a slight improvement over the callback-style approach above, but it is much clearer if you are able to use async/await:
async function logAfter(message, delay) {
return new Promise(resolve => {
setTimeout(() => {
console.log(message);
resolve();
}, delay);
});
}
async function logNAfter(message, times, delay) {
for (let i = 0; i < times; ++i) {
await logAfter(message, delay);
}
}
async function demoSequence1() {
await logAfter('Hello', 1000);
await logAfter('There', 1500);
}
async function demoSequence2() {
await logNAfter('Hi There!', 3, 500);
await logAfter('Goodbye!', 2000);
}
Hope that helps!
I like Williams suggested of breaking it down into different timers that could be controlled easier by the user. However, using this approach, I personally ran into the issue of how to pause the timer.
I decided to take a slightly different approach. From the table given, there is a fairly clear pattern of how the timer needs to be set up.The timer generally alternates between "Workout time" and "Rest time" for the whole duration. Rest time can take 3 different values:
Rest time between exercises
Rest time between Sets
The workout is complete
Since all of these values are known when the the values are inputed, my approach is set up the course of the timer before starting the timer. This creates a little bit of setup time but I believe this is negotiable and will not impact performance heavily. To do this, I created a created an array before starting the timer. Each item in this array contains data including the total time remaining, the current set, the label (Working out or resting), and the label timer. After creating this array, we can just create a timer that is based off the number of items in the array. I hope that this little explanation helps you understand my solution a little bit better.
Index.html
<!DOCTYPE html>
<html>
<style>
td, th {
text-align: left;
padding: 8px;
}
</style>
<head>
<title>Timer</title>
</head>
<body>
<!-- Inputs -->
<h2>Inputs</h2>
<p>
<label for="sets-input">Number of Sets: </label>
<input type="number" id="sets-input" min="1" max="3600">
</p>
<p>
<label for="exercises-input">Number of Exersizes per Set: </label>
<input type="number" id="exercises-input" min="1" max="3600">
</p>
<p>
<label for="workout-input">Exersise Time: </label>
<input type="number" id="workout-input" min="1" max="3600">
</p>
<p>
<label for="exersiseRest-input">Rest between exersises: </label>
<input type="number" id="exersiseRest-input" min="1" max="3600">
</p>
<p>
<label for="setRest-input">Rest between Sets: </label>
<input type="number" id="setRest-input" min="1" max="3600">
</p>
<!-- Buttons -->
<p>
<button id="start-button">Start</button>
<button id="reset-button">Reset</button>
</p>
<!-- Timer Display -->
<h2>Outputs:</h2>
<table>
<tr>
<th>Total Time Remaining: </th>
<td id="timer-display">???</td>
</tr>
<tr>
<th>Set Number: </th>
<td id="set-display">???</td>
</tr>
<tr>
<th id="label-display">???</th>
<td id="labelTimer-display">???</td>
</tr>
</table>
<script src="tabada.js"></script>
</body>
</html>
Tabada.js
//-----------------------------------------------------------------------------------------------
// GLOBAL VARIABLES
//-----------------------------------------------------------------------------------------------
// HTML
var setsInput = document.getElementById("sets-input");
var exersisesInput = document.getElementById("exercises-input");
var workoutInput = document.getElementById("workout-input");
var exersiseRestInput = document.getElementById("exersiseRest-input");
var setRestInput = document.getElementById("setRest-input");
var timerDisplay = document.getElementById("timer-display");
var setDisplay = document.getElementById("set-display");
var labelDisplay = document.getElementById("label-display");
var labelTimerDisplay = document.getElementById("labelTimer-display");
var startButton = document.getElementById("start-button");
var resetButton = document.getElementById("reset-button");
// JavaScript
var sets = 2;
var exersises = 3;
var workout = 5;
var exersiseRest = 2;
var setRest = 3;
var totalTime = -1;
var myInterval = -1;
var tabadaArray = [];
var tabadaIndex = 0;
//-----------------------------------------------------------------------------------------------
// BUTTON FUNCTIONS
//-----------------------------------------------------------------------------------------------
// Start / Pause Button
startButton.addEventListener("click", function(event){
// Set up Tabada Timer
if (totalTime == -1){
collectInputs(); // Comment this line for testing without inputs
calculateTotalTime();
createTabadaArray();
}
// Start timer
if (myInterval == -1){
startButton.innerHTML = "Pause";
myInterval = setInterval(tabadaTimer, 1000);
}
// Pause timer
else{
startButton.innerHTML = "Start";
clearInterval(myInterval);
myInterval = -1
}
});
// Reset Button
resetButton.addEventListener("click", function(event){
// Stop Timer
clearInterval(myInterval);
// Refresh Timer Display
calculateTotalTime();
updateOutputs(totalTime, 1, 'Workout', workout);
totalTime=-1; // Alows user to change input values before clicking start button.
// Reset start / pause button
myInterval = -1;
startButton.innerHTML = "Start";
});
//-----------------------------------------------------------------------------------------------
// SETUP FOR TABADA TIMER
//-----------------------------------------------------------------------------------------------
function collectInputs(){
sets = parseFloat(setsInput.value);
exersises = parseFloat(exersisesInput.value);
workout = parseFloat(workoutInput.value);
exersiseRest = parseFloat(exersiseRestInput.value);
setRest = parseFloat(setRestInput.value);
}
function calculateTotalTime(){
let totalWorkoutTime = workout * exersises * sets;
let totalExersiseRest = exersiseRest * (exersises - 1) * sets;
let totalSetsRest = setRest * (sets - 1);
totalTime = totalWorkoutTime + totalExersiseRest + totalSetsRest;
}
function createTabadaArray() {
tabadaIndex = 0; // Global variable used for tabada timer
tabadaArray = [];
for( let set=1; set<=sets; set++ ){
for( let exersise=1; exersise<=exersises; exersise++){
// Workout
addTimeBlock(set, 'Workout', workout);
// Exersise Rest
if ( exersise < exersises){
addTimeBlock(set, 'Rest', exersiseRest);
}
// Set Rest
else if( set < sets){
addTimeBlock(set, 'Rest', setRest);
}
// Done
else{break;} // Very end exersize has no rest, so we must break the loop.
}
}
}
function addTimeBlock(set, label, labelTime) {
// Add a sub timer to the array (workout, exersice rest, or set rest)
for (let i=labelTime; i>0; i--) {
tabadaArray.push({
"totalTimeRemaining" : totalTime--,
"set" : set,
"label" : label,
"labelTimeRemaining" : i,
});
}
}
//-----------------------------------------------------------------------------------------------
// TABADA TIMER
//-----------------------------------------------------------------------------------------------
function tabadaTimer(){
// Still time left
if (tabadaIndex < tabadaArray.length){
let displayInfo = tabadaArray[tabadaIndex];
updateOutputs( displayInfo.totalTimeRemaining,
displayInfo.set,
displayInfo.label,
displayInfo.labelTimeRemaining );
tabadaIndex++;
}
// End of tabada timer
else{
clearInterval(myInterval); // stop timer
updateOutputs(0, 1, 'Rest', 0);
totalTime = -1
}
}
function updateOutputs(totalTimeRemaining, setNumber, label, labelTimeRemaining){
timerDisplay.innerHTML = convertSeconds(totalTimeRemaining);
setDisplay.innerHTML = setNumber;
labelDisplay.innerHTML = label;
labelTimerDisplay.innerHTML = convertSeconds(labelTimeRemaining);
}
function convertSeconds(s){
// Seconds -> mm:ss format
// Calculate
let minutes = Math.floor(s/60);
let seconds = s%60;
// Format
let formattedminutes = ("0" + minutes).slice(-2);
let formattedseconds = ("0" + seconds).slice(-2);
return formattedminutes + ':' + formattedseconds;
}

How to get a working countdown timer with a button that adds +1 to a counter after every click

I am setting up a project for class which I need to use jquery. I have settled on a project whereby you would click the button, the counter would increase by one and a timer would start. This would act like a game to see how fast you can click in 10 seconds.
$("#button").mousedown(function () {
score = score + 1;
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span>0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
I expected the timer to start and the counter to increase by one but nothing happens at all.
You need to:
Add an id to your button:
<button id="button" type="button" name="button">Click</button>
Also you need to define the score & stop variables globally outside the function:
var score = 0;
var stop = 0;
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var score=0;
var stop=0;
var counter = 0;
var endscore=0;
$("button").mousedown(function () {
score = score + 1;
$("#score").text(score);
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
// $("button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#timeRemaining').text(display);
}, 1000);
}
};
});
</script>
</head>
<body>
<div class="clicks">
<p><span id="score">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span id="timeRemaining">60</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
</body>
</html>
You're using as selector an ID, however your button element doesn't have that ID. You can do the following:
Add the id to that button.
Or, you can change the selector as:
$(".but").mousedown(function() { // or $('button[name="button"]').mousedown(function() {...});
score = score + 1;
startTimer();
});
From your html you didn't have id="button" so use name selector or assign id to the button.
Like below.
$("input[name='button']").mousedown(function() {
score = score + 1;
startTimer();
});
You forgot to initialize some variables and give some ids.
var score = 0
var stop = 0
$("#button").click(function () {
score = score + 1;
startTimer();
});
function startTimer() {
console.log('start timer')
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
console.log('#interval')
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#counter').html(counter)
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span id="counter">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
</div>
<div class="but">
<button type="button" id="button">Click</button>
</div>

Why doesn't my timer function count down?

I am working on a personal project to create a pomodoro clock. I am starting off by trying to create a 25 minute countdown timer with a start and stop button. I have included a timer function that should count down my variable every 1000 milliseconds but it does not function. Here is my HTML:
Pomodoro Clock
<div id="timer" class="circle">Timer</div>
<button onclick="setTimeout(timer, 1000);">Start</button>
<button>Stop</button>
Javascript:
var i = 25;
document.getElementById("timer").innerHTML = i;
function timer(){
setInterval(function(){i--}, 1000);
}
I am guessing it may have something to do with my timer function?
document.getElementById("timer").innerHTML = i;
Here the current value of i is being assigned to innerHTML. It's not being passed by reference.
The only data types in JavaScript that are passed by reference are Objects (Plain objects, functions, arrays, etc).
You need to assign the new value of i to innerHTML on every iteration of your interval:
setInterval(function(){
i--;
document.getElementById("timer").innerHTML = i;
}, 1000);
You need to update the innerHTML inside the setInterval() callback. Also you can clear the interval using clearInterval(). I just removed the setTimeout() , since setInterval() starts after the delay.
var i = 25,
ele = document.getElementById("timer");
ele.innerHTML = i, inter;
function timer() {
inter = setInterval(function() {
ele.innerHTML = --i;
if (i == 0) clearInterval(inter);
}, 1000);
}
function stop() {
clearInterval(inter);
}
<div id="timer" class="circle">Timer</div>
<button onclick="timer()">Start</button>
<button onclick="stop()">Stop</button>
Try this
var i = 25;
function timer(){
setInterval(function(){
i--;
document.getElementById("timer").innerHTML = i;
}, 1000);
}
You only set the innerHTML one time, at the start of the script. You need to do it each time your function runs.
document.getElementById("timer").innerHTML = i;
function timer(){
setInterval(function(){
i--;
document.getElementById("timer").innerHTML = i;
}, 1000);
}
You need to update the div inside the interval function.
var i = 25;
var timerDiv = document.getElementById("timer");
function timer() {
setInterval(function() {
timerDiv.innerHTML = i--;
}, 1000);
}
.circle {
background-color: red;
color: white;
border-radius: 20px;
display: inline-block;
width: 40px;
height: 40px;
text-align: center;
font-weight: bold;
font-family: sans-serif;
line-height: 40px;
}
<div id="timer" class="circle">Timer</div>
<button onclick="setTimeout(timer, 1000);">Start</button>
<button>Stop</button>

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