I need a pause button for this timer. And unfortunately, it's not working.
When id "button-pause" is clicked, I need to set "var pressed = true".
If not, run the script below "if(!pressed){" and let "var pressed = false".
What's wrong?
HTML
<span id="button-pause">
<span class="music"></span>
<img src='img/icons/pause.png' alt='Stop music'>
</span>
JavaScript
var minutes = 60;
// Set number of seconds remaining after which to trigger a warning color
var warning = 59;
var pressed = false;
k = document.getElementById('button-pause');
k.onclick = function () {
pressed = true;
}
if(!pressed){
// Declare variables
var timerEl, seconds, timer;
// Get a reference to the HTML element
timerEl = document.getElementById('tim');
// Calculate total seconds
seconds = 1*minutes;
// Updates the timer element
function updateTimer() {
var m,s;
// Get whole minutes
m = Math.floor(seconds/60);
// Get left-over seconds
s = seconds % 60;
// Pad anything below 10 with a leading zero
s = (s < 10) ? "0"+s : s;
// Write time to HTML element
timerEl.innerHTML = m + ":" + s;
// Decrement seconds
seconds--;
// Add warning class when we hit threshold
if(seconds < warning) {
timerEl.classList.add('warning');
}
// Clear timer when we hit zero
if(seconds < 0) {
clearInterval(timer);
window.location.href='index.php?mode=workout&workoutid=test&status=done';
}
}
}
timer = setInterval(updateTimer, 1000);
Your first problem is using the same variable for two things
var pressed = false; <-- store a boolean
pressed = document.getElementById('button-pause'); <--override the boolean with the button
Second issue is the JavaScript code is not going to change when you click the button. It will set the variable, but the code that has already run will not update magically. You would need to add the code to some sort of function and trigger it when the button is clicked or when the page is loaded.
Related
I want to make a countdown in javascript, with simple variables, for loop, set timeout.
I get stuck when trying to make a for loop update realtime (every second) right now I get -1 in webpage.
//HTML PART
<p id=timer>0</p>
//JS PART
var timer = 10;
var text = "";
function f() {
for (timer; timer > 0; timer--) {
text += timer + "<br>";
}
timer--;
if( timer > 0 ){
setTimeout( f, 1000 );
}
}
f();
document.getElementById("timer").innerHTML = timer;
Please explain the error and if I'm doing any stupid mistakes
Looks like you want to show timer value from 10 to 0 by changing the value every second. If so, you can do like this:
1. You need to correct your html by putting quotes around timer like this <p id="timer">0</p>
2. You need to remove for loop as I have commented.
3. Move document.getElementById("timer").innerHTML = timer; inside function f().
var timer = 10;
//var text = "";
function f() {
//for (timer; timer > 0; timer--) {
// text += timer + "<br>";
//}
document.getElementById("timer").innerHTML = timer;
timer--;
if (timer >=0) {
setTimeout(f, 1000);
}
}
f();
<p id="timer">0</p>
You can do it like so, I provided comments in code for explanation:
var count = 10;
function timer(targetValue) {
// display first number on screen
document.getElementById("timer").textContent = count;
// decrease count by 1
count--;
// check if timer is still grater than target value
if (count >= targetValue) {
// call timer() function every second to update
setTimeout(timer, 1000, targetValue);
}
}
timer(0);
Counts down from 10 to 0.
Want to count down from 10 to 5? Simply use timer(5)
I'm trying to make a stopwatch. Here's the code:
var min = 0, sec = 0, censec = 0
$("#startBtn").on("click", function() { // when start button is clicked
$(this).hide(); // start is hidden
$("#stopBtn").show(); // stop is shown
setInterval(add, 10); // the censec will be increased every 10 millisecond.
$("#censec").text(censec);
})
function add() {
censec++;
if (censec == 100) {
censec = 0;
sec++;
if (sec == 60) {
sec = 0;
min++;
}
}
}
The problem is that setInterval() happens only at once. The censec only changes from 00 to 1. That's it.
P.S. I'm new to coding, so if there are other mistakes, please don't hesitate to tell me.
The setInterval calls to add will definitely repeat. But your code is only ever showing the value of censec once, when you start the timer.
If you want to update the display every hundredth of a second, put the code showing the value in add.
Separately, the code as it is in the question won't run at all, because it has a ReferenceError on the first line. Those ; should be ,.
Example (this also stores the timer's handle and clears the timer when you click the stop button):
var min = 0, sec = 0, censec = 0;
// Note ---^--------^
function add() {
censec++;
if (censec == 100) {
censec = 0;
sec++;
if (sec == 60) {
sec = 0;
min++;
}
}
$("#censec").text(censec);
}
var timer = 0;
$("#startBtn").on("click", function() { //when start button is clicked
$(this).hide(); //start is hidden
$("#stopBtn").show(); //stop is shown
timer = setInterval(add,10); //the censec will be increased every 10 millisecond.
});
$("#stopBtn").on("click", function() {
clearInterval(timer);
timer = 0;
$(this).hide();
$("#startBtn").show();
});
<input type="button" id="startBtn" value="Start">
<input type="button" id="stopBtn" value="Stop" style="display: none">
<div id="censec"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that although it may be mostly fine to use setInterval for displaying, using it to track the elapsed time is a bad idea; it frequently doesn't fire precisely.
Instead, record when you started
var start = Date.now();
...and then when the timer fires, figure out how long it's been since you started
var elapsed = Date.now() - start;
Then use the value (milliseconds) in elapsed to figure out your display.
Your variable declarations have ; instead of , .
Also checking numbers on equality should be done by using === but that is not the problem here.
Your also not updating the view in your timer. So updating of your html should also be in your function that is called by the timer.
If the goal is to use real seconds and milliseconds, I also suggest using the Date type because your timer will be late and not real-time. So still use the timer with the interval you like but in the add function you call the date object. You can replace the 3 vars for one datetime of type Date which will give you the granularity that you like.
var dateTimeStart = null, censecElement = null, timer = null;
$("#startBtn").on("click", function() {//when start button is clicked
$(this).hide(); // start is hidden
$("#stopBtn").show(); // stop is shown
if(timer === null) {
// timer was not started
dateTimeStart = new Date();
timer = setInterval(updateCensec, 10); //the censec will be increased every 10 millisecond.
console.log("Started timer");
}
});
$("#stopBtn").on("click", function() {//when stop button is clicked
$(this).hide(); // stop is hidden
$("#startBtn").show(); // start is shown
if(timer) {
// timer is started/running
clearInterval(timer);
console.log("Stopped timer");
}
timer = null;
});
function updateCensec() {
var sensec = 0, sec = 0, dateTimeNow = new Date(), diffMilliseconds = 0;
diffMilliseconds = dateTimeNow - dateTimeStart;
censec = parseInt((diffMilliseconds % 600 ) / 10); // convert milliseconds to centi seconds
sec = parseInt(diffMilliseconds / 600);
if(censecElement === null) {
censecElement = $("#censec");
}
censecElement.text(sec + ":" + censec);
}
I would like to suggest that you do not update your view every 10 milliseconds even if you want your stopwatch to show time in centiseconds.
I am not sure if this possible using my current method, but I am wondering if it is possible to show the timeout as a counter on page.
I am creating a page to show data entering the database in 15 second intervals however the timeout can be changed.
var counter = 15 * 1000
var autoRefresh = function(){
clearInterval(interval);
interval = setInterval(autoRefresh, counter);
$.pjax.reload({container:"#content",async:false, timeout: 2000});
return false;
}
var interval = setInterval(autoRefresh, counter);
Ideally I need to show a countdown timer till the next refresh. Is it possible or is there an alternate route I can take to achieve this?
The only real way is to run your interval every second, display the countdown and, if 15 seconds have past, do what you want to do.
var counter = 15 * 1000;
var currentCycle = 0;
var autoRefresh = function(){
currentCycle++;
if (currentCycle >= (counter/1000)) {
currentCycle = 0;
$.pjax.reload({container:"#content",async:false, timeout: 2000});
} else {
console.log((counter/1000-currentCycle)+' seconds remaining');
}
return false;
}
var interval = setInterval(autoRefresh, 1000);
I have a game that I am making using only pure javascript. Instead of a GUI, It is more like the old command line games and uses a prompt for input.
One of the main components of it is the Clock, which is expressed in hours, and can be checked with the commmand "time" and tells them the value of the variable "time". Here is the code:
var timestrt = 1;
var timer = setInterval(function(){timestrt++;return timestrt;}, 86000); var time = timestrt;
After testing it, I realized that the clock was not changing. So I set it to 10 seconds instead of 86 to be sure that I was waiting long enough, and it still did not want to work
I know that it is probably caused by the prompt and constant alerts, but I am not sure even where to start for a workaround.
Any ideas?
Edit: is it possible to either
1. retrieve the timer from an external page
2. comparing it to an actual clock in real time or 3. Using a animated gif clock in the background and calculating the location of certain pixels as time?
Don't use the native prompts and dialogs, since they stop the script execution time. Instead use simulated ones, for example jQuery IU has prompts and dialog boxes that do not stop execution. Here is an example of that:
$(function() {
$( "#dialog" ).dialog();
var timestrt = 1;
var timer = setInterval(function(){
timestrt++;
var time = timestrt;
$("#time").text(time);
}, 1000);
});
Here is my workaround:
This code is called before the prompt is started:
function initTime() {
var now = new Date();
stS = now.getSeconds();
stM = now.getMinutes();
stH = now.getHours();
}
This is called after the prompt is done:
function computeTime() {
var now = new Date();
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
Then I convert it to seconds to make it easier to check against:
var finalH = elapH * 3600;
var finalM = elapM * 60;
var finalS = finalM + elapS + finalH;
And check/change the time variable based on how many sets of 86 seconds has passed:
if (finalS > 86 && finalS < 172) {
time = 1;
}
if (finalS > 172 && finalS < 258) {
time = 2;
}
if (finalS > 258 && finalS < 344) {
time = 3;
}
if (finalS > 344 && finalS < 430) {
time = 4;
}
if (finalS > 430 && finalS < 516) {
time = 5;
}
if (finalS > 516) {
time = 6;
alert('5 A.M.');
alert('A clock is chiming...');
alert('6 A.M.');
playing = false;
alert('Thanks for playing! Goodbye!');
}
And that is my alternative to using a setinterval/timer behind multiple prompts and alerts. The last part probably wasn't needed, but since it answered my original question I included it.
I have created a very simple countdown timer in js which every element of time is calculated out. It works, the only issue with it is there exists lag most likely caused from the calculations being made every second. Any thoughts as to how to make this more efficient?
js:
var count = 55010; //needs to be in seconds
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer(){
count = count-1;
if (count <= -1){
clearInterval(counter);
return;
}
document.getElementById("hour10").innerHTML=Math.floor(((count/86400)%1)*2.4);
document.getElementById("hour1").innerHTML=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10;
document.getElementById("min10").innerHTML=Math.floor(((count/3600)%1)*6);
document.getElementById("min1").innerHTML = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10;
document.getElementById("sec10").innerHTML = Math.floor(((count/60)%1)*6);
document.getElementById("sec1").innerHTML = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10;
}
HTML:
<span id="hour10">0</span>
<span id="hour1">0</span> :
<span id="min10">0</span>
<span id="min1">0</span> :
<span id="sec10">0</span>
<span id="sec1">0</span>
The reason I have created the timer in this fashion is because I want to put each element into a div container like so:
Thanks in advance!
A way to make this more efficient is to keep a reference to the elements by only searching the Dom once, and also use innerText if you are not using any markup
var count = 55010; //needs to be in seconds
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
var elHour10 = document.getElementById("hour10");
var elHour1 = document.getElementById("hour1");
var elMin1 = document.getElementById("min10");
var elSec10 = document.getElementById("sec10");
var elSec1 = document.getElementById("sec1");
function timer(){
count = count-1;
if (count <= -1){
clearInterval(counter);
return;
}
elHour10.innerText=Math.floor(((count/86400)%1)*2.4);
elHour1.innerText=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10;
elMin10.innerText=Math.floor(((count/3600)%1)*6);
elMin1.innerText = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10;
elSec10.innerText = Math.floor(((count/60)%1)*6);
elSec1.innerText = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10;
}