Why does this debounce and Interval not work? - javascript

var counter;
var count = 0;
window.onload = function() {
document.getElementById('myid').addEventListener("click", debounce(e => {
console.log('clicked');
start(document.getElementById('myid').className, document.getElementById('myid').value);
}, 200))
/*
x=document.getElementById('myid');
x.onclick= debounce(function()
{
console.log(x.classname,x.value);
start(x.className, x.value);
}, 200);
*/
}
const debounce = (fn, delay) => {
let timeoutID;
return function(...args) {
if (timeoutID) {
clearTimeout(timeoutID);
}
timeoutID = setTimeout(() => {
fn(...args)
}, delay);
};
};
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
clearInterval(counter);
}
function add(clicked_className, Zeichen) {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
}
<!DOCTYPE html>
<html onmouseup="end()">
<form name="Rechner">
<button id="myid" class="zahlen" value=" 7 ">Click</button>
<input type="text" name="Display" value=" 7 " class="display" readonly>
</form>
</html>
I have to do this for school but I edit and try but no matter what I do it seems to not work =/
It doesnt even give me any errors.
Also tried the debounce and interval each in small scale and it worked...
My problems started when trying to make debounce work with an actual function instead of an anonymous function with only console log in it.
I cant even identify the problem

From what you have described, I'd do something like this. However, I'm not sure, if that really is, what you are looking for. So if it isn't: please specify your needs.
const startButton = document.getElementById('start-button');
const stopButton = document.getElementById('stop-button');
const display = document.getElementById('display');
const firstDelay = 1000;
const intervalDelay = 200;
let interval;
function addValue() {
display.value += `${startButton.value}`;
}
function stop() {
if(interval) {
clearInterval(interval);
}
}
function start() {
setTimeout(() => {
interval = setInterval(addValue, intervalDelay);
}, firstDelay);
}
startButton.addEventListener("click", start);
stopButton.addEventListener("click", stop);
<button id="start-button" value="7">Click</button>
<button id="stop-button">Stop</button>
<input type="text" id="display" value="7" class="display" readonly>

Related

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

TypeScript variables are undefined even after i initialized them in constructor. Full typescript code is provided below

I have some variables like seconds, miliseconds, minutes, interval etc.
I am initializing all variables in constructor and using them in startinterval, stopinterval functions.
On window load I have called init function and attached events to button based on their id, but when I click start button undefined error is raised on this.timerId.
Html and type script code is provided below.
Need to know what I am doing wrong.
HTML Code
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Index.js"></script>
</head>
<body>
<h1>Timer</h1>
<a id="minutes">1</a><a id="seconds">1</a><a id="miliseconds">1</a>
<button id="btnStart" value="Start" >Start</button>
<button id="btnPause" value="Pause" >Pause</button>
<button id="btnStop" value="Stop" >Clear</button>
</body>
</html>
JS Code
class Timer {
seconds: number;
miliseconds: number;
minutes: number;
interval: number;
timerId: number;
constructor() {
this.seconds = 0;
this.miliseconds = 0;
this.minutes = 0;
this.interval = 25;
this.timerId = -1;
}
startTimer = function () {
if (this.timerId == -1) {
window.setInterval('this.timerActivate()', this.interval);
}
};
pauseTimer = function () {
window.clearInterval(this.timerId);
this.timerId = -1;
};
stopTimer = function () {
this.pauseTimer();
this.miliseconds = 0;
this.seconds = 0;
this.minutes = 0;
this.displayTimer();
};
displayTimer = function () {
document.getElementById('miliseconds').innerHTML = this.miliseconds.toString();
document.getElementById('seconds').innerHTML = this.seconds.toString();
document.getElementById('minutes').innerHTML = this.minutes.toString();
};
timerActivate = function () {
this.miliseconds += this.interval;
if (this.miliseconds >= 1000) {
this.miliseconds = 0;
this.seconds += 1;
}
if (this.seconds >= 60) {
this.miliseconds = 0;
this.seconds = 0;
this.minutes += 1;
}
this.displayTimer();
};
init = function (startButton: string, pauseButton: string, clearButton: string) {
document.getElementById(startButton).addEventListener('click', this.startTimer, false);
document.getElementById(pauseButton).addEventListener('click', this.pauseTimer, false);
document.getElementById(clearButton).addEventListener('click', this.stopTimer, false);
this.displayTimer();
}
}
window.onload = function () {
var timer = new Timer();
timer.init("btnStart", "btnPause", "btnStop");
}
Because your context (this) changes when you use the function () {} syntax or pass an unbound function reference. You can do a couple of things.
Change your function definitions to use arrow functions:
startTimer = () => {
if (this.timerId == -1) {
window.setInterval('this.timerActivate()', this.interval);
}
};
Or wrap your event listeners inside an arrow function:
document.getElementById(startButton).addEventListener('click', () => this.startTimer(), false);

counter in seconds idle jquery

i have this function in Idle library, but what i need is to calculate the action time in second, i mean the active time(onclick, onscroll and keypress).
function is:
(function () {
var minutes = false;
var interval = 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;
var counter=0;
document.onclick = document.onkeypress = function () {
idleCounter = 0;
setInterval(function () {
++counter;;
}, 1000);
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
}());
this function will wait for 5 seconds, if no action on the page, so i will be redirected to SessionExpired.aspx. if there is action, so am doing ++couter each second.
I need when this counter in seconds.
Thank you.
You can just reset the timer
var counter;
var counterSeconds;
document.onclick = document.onkeypress = function () {
idleCounter = 0; // Set counter to 0 on each keypress/page click
clearInterval(counter) // Every time they click, clear the old interval and start a new one below
counter = setInterval(function () { // assign the interval to a variable so we can clear it
if (idleCounter > IDLE_TIMEOUT) { // Check if they've idled too long
document.location.href = "SessionExpired.aspx"; // Redirect them if they have
}
++counterSeconds;
++idleCounter; // Should increment 1/sec depending on your computer.
}, 1000); // Ticks at 1000 milliseconds (1 Second)
};
One problem here is that you start new interval function for each click or keypress event which causes multiple threads to update same variable.
You should start an interval thread outside the event.
try this:
document.onclick = document.onkeypress = function () {
idleCounter = 0;
};
var activeTimer = setInterval(function () {
++counter;
}, interval);
var idleTimer = window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
This is what i wanted exactly and i did it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script>
<script src="./e-lawyer/JS/idle.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
var it;
x = 0;
$(document).ready(function(){
$('.status').html('active');
});
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 2000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>

Javascript timer not working..

Here is my code, please tell me where I've made a mistake so I can learn from it and hopefully get it working :).
Here is the html:
<input type="text" id="txt" />
<input type="button" value="Start Timer" onclick="startTimer()" />
And here is the javascript:
var Timer = 120;
var checkTimer = false;
var t;
function countDown(){
doucment.getElementById("txt").value = Timer;
Timer--;
t = setTimeout("countDown();", 1000);
}
function startTimer(){
if(!checkTimer){
checkTimer = true;
countDown();
}
else{
console.log("Error!");
}
}
Looking into your code in this Fiddle
Had me stumble across a few things,
The startTimer() in the onclick wasn't found.
doucment !== document as pointed out by Sterling Archer
The string eval could be changed to t = setTimeout(countDown, 1000); also pointed out by Sterling Archer
Now let's go to the solution.
HTML
<input type="text" id="txt" />
<!-- Removed the onclick attribute and added an ID for the eventListener -->
<input type="button" value="Start Timer" id="start" />
JS
//Event listener for the button. Same as the onClick, this one, however, does work.
document.getElementById("start").addEventListener("click", startTimer, false);
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
Timer--;
t = setTimeout(countDown, 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
What I've done is:
I've added an event listener to counter the startTimer() "cannot be found" error
I've changed doucment to document
and I've changed your string eval to t = setTimeout(countDown, 1000);
Hope this helps!
You have a typo. You should have document.getElementById("txt") not doucment.getElementById("txt"). Try this:
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
Timer--;
t = setTimeout("countDown();", 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
Update:
If you would like for the timer to stop at zero, you will need to add an if statement to see if the timer is greater than 0 before decrementing the timer again. That would look like this:
HTML:
<input type="text" id="txt" />
<input type="button" value="Start Timer" onclick="startTimer()" />
JS:
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
if (Timer > 0){
Timer--;
}
t = setTimeout("countDown();", 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
Demo: https://jsfiddle.net/hopkins_matt/moks2oyb/
Further improvements could be made to this code, but this is meant to illustrate that your code will work once the errors are fixed.

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