This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 months ago.
I am having trouble to find the way to stop this clock in JavaScript
I was expecting the clock to stop working after pressing stop but it keeps going
<!DOCTYPE html>
<html>
<head>
<h1> Welcome to the clock. Press the stop button to stop the clock <h1>
<h2> This clock goes for 24 hours at 100 miloseconds</h2>
<div id="clock"></div>
<script>
const clockElement = document.querySelector('#clock');
const stopButton = document.querySelector('#stopbutton');
let clockInterval = setInterval(() => {
let currentTime = new Date();
clockElement.innerHTML = currentTime.toLocaleTimeString();
}, 100);
stopButton.addEventListener('click', () => {
clearInterval(clockInterval);
});
</script>
<button id="stopbutton">Stop</button>
The code in the script tag is running before the browser "rendered" the button.
You should put the button element above the script tag or tell the code to wait until the entire website has loaded with window.onload
Move this to the end of code should work, it will explain what happened
<script>
const stopButton = document.querySelector('#stopbutton');
stopButton.addEventListener('click', () => {
clearInterval(clockInterval);
});
</script>
Related
I created a simple test page for a timer that counts down from 10 to 0. There should be a bar as well as text showing the progress. So I created this page:
<html>
<head>
</head>
<body>
<script>
function ProgressCountdown(timeleft, bar, text) {
return new Promise((resolve, reject) => {
var countdownTimer = setInterval(() => {
timeleft--;
document.getElementById(bar).value = timeleft;
document.getElementById(text).textContent = timeleft;
if (timeleft <= 0) {
clearInterval(countdownTimer);
resolve(true);
}
}, 1000);
});
}
</script>
<div>
<div>
<progress value="10" max="10" id=pageBeginCountdown"></progress>
<p> Beginning in <span id=pageBeginCountdownText">10 </span> seconds</p>
</div>
</div>
</body>
</html>
It is not working, both bar and text do not budge. Where did I go wrong? The page is at https://geheimbund.ddnss.de/test.html - I have been debugging this for hours, but I just cannot get it to work. Would be super-thankful for any help.
I tried everything I could think of. I expect this to work, i.e. the bar and the text should count down to 0.
Based on the posted code alone, you would need an event that runs your function.
Also, as pointed out, the functions' variables aren't defined.
window.addEventListener('load', () => {
ProgressCountdown();
});
I'm trying to get the date to appear in an empty paragraph with an ID when I click on a button. So far no luck. Don't mind if I cant get it to appear in the paragraph but just want to know how to make it appear when I click the button thanks in advance.
sorry if its a dumb one,
I have got the alert working on click but just can not seem to figure this one out
<!DOCTYPE html>
<html>
<head>
<title>Lets Practice Some Code</title>
<link rel="stylesheet" type="text/css" href="/Users/Matteveli/Desktop/javascript practice/style/style.css">
</head>
<body>
<div><h1 id="topTitle"> Time and date Test</h1></div>
<div><button id="alerter">click Me to make an alert pop up.</button></div>
<p id="empty"
></p><div><button id="timeAndDate">click Me to display time and date</button></div>
<script type="text/javascript" src="/Users/Matteveli/Desktop/javascript practice/javascript/funtionality.js"></script>
</body>
<footer>
</footer>
</html>
var alerterButton = document.getElementById("alerter");
var dateButton = document.getElementById("timeAndDate");
var emptyP = document.getElementById("empty");
var d = new Date();
// for the first click that we have working.... " THE ALERT "
//a link to function was called then the function was made
// as below
alerterButton.onclick = myClickHandler;
function myClickHandler() {alert("the document was clicked")};
/// TIME AND DATE ???
dateButton.onclick = emptyP.innerHTML=d;
function showMeTheDate() {emptyP.innerHTML+d};
any help greatly appreciated.
thanks in advance.
Here an example: http://jsfiddle.net/sckjnx7t/2/
The key is engage function and event, in this case onclick, then, you could do:
dateButton.onclick = function(){
//code here
};
or:
dateButton.onclick = showMeTheDate();
function showMeTheDate() {
//code
};
dateButton.onclick should be a function. So, you should do
dateButton.onclick = () => { emptyP.innerHTML= d.getDate() }
Only edit your event handler function, and set pharagraph's innerHTML to d.getDate().
function myClickHandler() {
alert("button was clicked!");
emptyP.innerHTML = d.getDate();
}
You need to stay the function workers in same scope. Without this approach, the latest eventHandler function will be used for all time, because other (last) functions' functionality won't be.
I want to show loader that will show the time in seconds while loading the app. Here is the code
HTML
<body>
<div class="app-loader">
<div class="loader-spinner">
<div class="loading-text"></div>
</div>
</div>
<angular-app></angular-app>
</body>
Javascript
(function loader() {
var elAppLoader = document.querySelector("app-loader");
var startTime = new Date();
var counter = setInterval(() => {
var seconds = Math.abs((new Date().getTime() - startTime.getTime()) / 1000);
var elLoadingText = document.querySelector(".loading-text");
elLoadingText.innerHTML = seconds.toFixed(2) + " s";
}, 100);
elAppLoader.addEventListener('app-loaded', function (event) {
clearInterval(counter);
elAppLoader.remove();
});
})();
Now this works fine and shows the no of seconds on the screen after every 100ms but when the angular start loading the counter freezes until the angular gets loaded.
How can I solve this? Is this because JS is single threaded if so is there any way to achieve this?
Yes this is beacause browser is busy parsing angular and all the loaded js.
The way to solve this is to use web worker.
Read more about it here: https://www.w3schools.com/html/html5_webworkers.asp
It has a working timer example which suits your case
This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 7 years ago.
My code:
<!DOCTYPE html>
<html>
<body>
<button id="start" onClick="myFunction()">Start</button>
<div id="output"></div>
<script>
function myFunction() {
for(i=3; i>0; i--) {
console.log(i);
document.getElementById('output').innerHTML = i;
pause(5000);
}
}
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
</script>
</body>
</html>
Numbers 3, 2 and 1 appear in console at intervals of 5 seconds, but in div appear number 1 (actually all numbers) after 15 seconds. Why console is not synchronized with display? Exist other method to stop rime between instructions?
The reason your function fails to work is, basically, that DOM changes arent processed and displayed until everything finishes running for a second. The easiest way to make it work would probably be a call to setTimeout which waits a specific amount of time then calls the supplied function. For example you could use the following function to make your code work.
This function recursively calls itself via a setTimeout call to make sure the DOM is udpated.
function myFunction(i) {
(function doStuff() {
console.log(i);
document.getElementById('output').innerHTML = i;
i -= 1;
if (i >= 0) {
setTimeout(doStuff, 5000);
}
}());
}
myFunction(3);
<div>
Counter: <span id="output">X</span>
</div>
I am trying to adapt the countdown timer from http://www.jqueryscript.net/time-clock/Simple-jQuery-Html5-Based-360-Degree-Countdown-Timer-countdown360.html to add buttons which determine the time to count down.
I am a little confused (no, really a lot confused) about
a) how to link the buttons to the countdown display,
b) how to stop the display starting until I have clicked the desired button, and
c) how to reset the process without reloading the page.
Currently it takes the initial seconds value of 10 (put there just to test to see what it is doing) but does not respond to the buttons.
Here is the html:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="../src/jquery.countdown360.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="container">
<div id="countdown"></div>
<script type="text/javascript" charset="utf-8">
$("#countdown").countdown360({
radius : 50,
seconds : 10,
fontColor : '#FFFFFF',
autostart : false,
onComplete : function () {//will ring bell
}
}).start()
</script>
<script>
window.onload = init;
function init(){
document.getElementById('btnStart1').onclick = start1;
document.getElementById('btnStart2').onclick = start2;
document.getElementById('btnReset').onclick = cdreset;
start.countdown360();
}
function start1(){ // starts 1 min countdown
seconds = 60;
countdown360();
}
function start2(){ // starts 2 min countdown
seconds = 120;
countdown360();
}
function reset() { // resets countdown
seconds=0;
//???
}
</script>
</div>
<div id="container">
<div id="countdown"></div>
<input type="button" value="1 min" id="btnStart1"/>
<input type="button" value="2 min" id="btnStart2"/>
<br>
<input type="button" value="Reset" id="btnReset"/>
</body>
</html>
Any help would be most welcome!
Answer & Demo
So it turns out there isn't a legit way of doing this, truth be told there isn't a lot of documentation about the subject and the plugin itself doesn't provide such functionability, or at least not in a user friendly way.
But I went down to the guts of the code and managed to make it work.
Here is a JSFiddle where I demonstrate what I understood you wanted.
HTML
<div id="countdown"></div>
<button id="start">Start</button>
<button id="set60">Set 60s</button>
<button id="set120">Set 120s</button>
<button id="reset">Reset</button>
JavaScript
start = document.querySelector("#start");
set60 = document.querySelector("#set60");
set120 = document.querySelector("#set120");
reset = document.querySelector("#reset");
div = $("#countdown");
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
pingSound.preload = "auto"; //<- Optional but recommended
countdown = div.countdown360({
radius: 50,
seconds: 30,
fontColor: '#FFFFFF',
autostart: false,
onComplete: function () {
pingSound.play();
}
});
countdown.start(); //This right here is for showing the clock on load.
countdown.stop();
start.onclick = function () {
startCountdown(countdown);
}
set60.onclick = function () {
setSeconds(countdown, 60);
}
set120.onclick = function () {
setSeconds(countdown, 120);
}
reset.onclick = function () {
setSeconds(countdown, 0);
}
function startCountdown(countdown) {
countdown.start();
}
function setSeconds(countdown, seconds) {
countdown.stop();
countdown.settings.seconds = seconds;
countdown.start();
}
Explanation
Variables
start, set60, set120, reset : Link to their respective button elements.
div : Link to the countdown div element.
pingSound : Audio element that contains the "ping" sound.
countdown : The countdown object itself, you need to declare it like this, passing the initial properties and saving it in a variable.
Functions
startCountdown(countdown) : Takes any countdown object and start's it's execution, this will get the countdown running.
setSeconds(countdown,seconds) : Takes any countdown object and set's it second (it can be used in mid-excecution). It works by first stopping the countdown, then updating the Countdown.settings.seconds property, which is the actual seconds the countdown will run.
Development
With those variables & methods, how I did it is pretty straight forward.
If you want the clock hidden until you play it:
We first create the countdown object and hide the div.
div = $("#countdown");
div.css( "display" , "none" );
countdown = div.countdown360({..});
Why? Well because of how the plugin works. As soon as you create the countdown your div is made bigger by the plugin, and you need to create the countdown there because that's the only way it works, so if you don't want a blank square of nothing (since we haven't started the countdown) you have to hide the div itself.
So, we add an onclick event to each button:
for start -> startCountdown(countdown) , div.css( "display" , "block" ); -> Starts the countdown and shows the div.
for set60 -> setSeconds(countdown,60) -> Sets the countdown to 60s.
for set120 -> setSeconds(countdown,120) -> Sets the countdown to 120s.
for set0 -> setSeconds(countdown,0) -> Sets the countdown to 0s.
And that's it, it took me a while to figure out, hopefully I didn't just bore you to death, and may I suggest getting a better plugin next time? Good luck :)
If you want the clock displayed on load:
Okey, so this is an update upon your request, if we part from my original code, to make the div appear on load is quite simple (JSFiddle & code here have been updated)
We first create the countdown object, then start it and inmeadiatly stop it (freezing it until you start it again).
countdown = div.countdown360({..});
countdown.start();
countdown.stop();
Now, we add the same onclick events to the buttons except for the start button, which will no longer have to display the div as block as it isn't hidden.
for start -> startCountdown(countdown) -> Starts the countdown.
(..)
If you want to play a sound at the end of the countdown:
For the ping sound to play in the end, you just need to create a new Audio object with the mp3/ogg src as a parameter:
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
Then, preload the audio so it's ready to play (otherwise when you call play it will first have to load). This is optional but recommended.
pingSound.preload = "auto";
And then call the Audio.play() function in the countdown's onComplete event.
countdown = div.countdown360({
(..)
onComplete:function(){
pingSound.play();
}
});
That's it, happy coding :)
Updates
Updated code to display the clock on load (1:43p.m 31/12/14)
Updated code to play sound in the end of countdown(6:10p.m 02/01/14)
First you don't have jquery.js and you are using $('#countdown')
You don't have any function called cdreset .
Well I wrote a similar code for you :
<script>
var m = setInterval(start, 1000), // init the interval , every 1 sec will call start function
s = 60;
function start(){
s = s -1;
document.getElementById("count").innerHTML = s;
}
function stop(){
clearInterval(m);
}
</script>
<p id="count">60</p>
<input type="submit" onclick="stop()" value="stop" />
it will count down starting from 60 to -XXX
You should add a condition so as to stop the timer at 0 :)