Stopwatch Not working - javascript

I found this stopwatch tutorial online, however when i tried implementing it, it kept saying "TypeError: start is null" and "TypeError: h1 is undefined" in the console when i inspect the element. What is bugging me even further is that when i insert the code in here it works and if i put it into notepad++ it does not work. Is there a jquery file that i might have missed during the implementation and some how snippet is making it work?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
<h1><time>00:00:00</time></h1>
<button id="start" >start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>

Wrap all your code, including functions, in a comon function that you could name initialize() { }.
Then, put on your <body> tag the function binded onload event like following :
<body onload="initialize()">
This will tell your code not to execute unless the whole DOM and element have been created, because you can't access your elements unless they are all fully loaded.

Likely, you have defined your Javascript BEFORE your HTML. Remember Javascript is a blocking language, so it will halt all operation (including loading the HTML) until the script is finished.
Move the script below your HTML or use some form of $(document)ready

Related

How do I start a timer on a click?

I'm trying to have a timer start when the user makes the first click on a page. Been doing a lot of research and for the life of me, can't figure it out. I think I should use a document.addEventListener but am not sure where it goes.
let min = 0;
let sec = 0;
function myTimer() {
if (counting) {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
}
//Start the timer
let startTimer = setInterval(function() {
myTimer();
}, 1000);
Just add a click listener to document that calls the setInterval:
let min = 0;
let sec = 0;
function myTimer() {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
//Start the timer
document.addEventListener('click', () => {
setInterval(myTimer, 1000);
}, { once: true });
<div id="timer">click somewhere</div>
Given a button with id button as so:
<button id="button">Click me</button>
the most basic way to add an event listener for that button to start the timer is by retrieving the element from dom (using querySelector or getElementById), then add a named event listener function to the element in the dom, such as onclick:
document.querySelector('#button').onclick = function(){
//your code to start timeer here
};
but you can also do it using addEventListener:
document.querySelector('#button').addEventListener('click',function(){
//your code to start timeer here
});
or with event delegation, you can add a global click handler to the document, check if the target element was the button, and if so you can then start the timer:
document.addEventListener('click',function(event){
if(event.target.id==='button'){
//your code to start timer here
}
});
there are 900 ways to skin a cat in modern javascript, its up to you to decide which one is most appropriate, and sometimes its a matter of personal preference.

Instead of script src address attribute put source directly

I have a code that's working:
if (typeof Checkout === 'object') {
if (typeof Checkout.$ === 'function') {
(function(src) {
var tagName = 'script',
script = document.createElement(tagName);
script.src = src;
var head = document.getElementsByTagName('head')[0];
head.insertBefore(script, head.childNodes[0]);
})('https://www.conversionpirate.com/pirate-countdown.js');
}
}
But I don't want to have reference to conversionpirate site since it's plain js that I can directly paste there. The problem is I don't know how to do it - I tried to put pirate-countdown.js code inside that method but failed. I'm sure it's quite easy, but required knowledge about it. Could someone help me with this one?
Work normally just by adding html element with main__header class and time id as beleow :
<script src="https://www.conversionpirate.com/pirate-countdown.js"></script>
<div class="main__header">
</div>
<div id="time">
</div>
Also if your still facing probleme make directly their code into your js file or just create new js file and refernce it loccally :
see below snipet :
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fragment3 = create('<div style="background:#fff5d2;padding:10px 20px;border:1px solid #e3df74; font-size:14px; color:#2c2c2c; font-weight:bold;-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin:10px 0px 20px 0px">Your order is reserved for <span id="time"></span> minutes!</div>');
document.getElementsByClassName('main__header')[0].appendChild(fragment3);
var ten = 60 * 10,
display = document.querySelector('#time');
startTimer(ten, display);
};
<div class="main__header">
</div>
<div id="time">
</div>

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_timer();
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

javascript function inside function not working

i have a timer script that i would like the user to be able to set the amount of time. it works when loading the script when the page loads and setting the timer to a default value, however when i create an input variable and a button to call the function it doesnt work. the "outside" function works however the code that i copy and paste from the working version into the function doesnt. it seems that the inside timer function is never called even though 'var countdownTimer = setInterval('secondPassed()', 1000);' is at the end of the outside function. ive been working on fixing it for hours, and i would like for a more experienced set of eyes to check it out. heres the code:
<script type="text/javascript">
function startTimer() {
var seconds = parseInt(document.getElementById("time").value);
document.getElementById('countdown').innerHTML = seconds;
function secondPassed() {
document.write(Date());
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
</script>
<input id="time" type="number">
<input type="button" value="Set Timer" onClick="startTimer()">
<span id="countdown" class="timer">Timer: </span>
</body>
the "Timer: " text is replaced by the value of the seconds variable but only because of the line before the inside function is defined. the Date() is not printed on the instide function
You're passing a string to setTimeout, so it gets evaluated and scope is broken. Only pass functions to setTimeout.
var countdownTimer = setInterval(secondPassed, 1000);

How to create a toggle button in Jquery-mobile?

I want my button to change color if clicked but it seems not working in this JQuery-Mobile. and If its clicked it seems like it increases the time count speed i dont know why.
Any help please guys.
var seconds = 0;
var minutes = 0;
var timer = null;
function toggle(ths) {
var clicked = $(ths).val();
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
$("#lblType").html(clicked);
$("#setCount").html(" minutes : " + minutes + " seconds : " + seconds);
//duration time
seconds = seconds + 1;
if (seconds % 60 == 0) {
minutes += 1;
seconds = 0;
}
timer = timer = setTimeout("toggle()", 1000);
}
try :
timer=setTimeout(function(){
toogle();
},1000);

Categories