I am trying to teach myself to code. I am coding a simple quiz. I would like my timer to fire on "start", and eventually, "next question". My timer starts once the page loads. Not sure why.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button id="b1">Click Me!</button>
<p id="demo"></p>
<script>
var sec = 5;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById("b1").onclick = function() {
myTimer()
};
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(time);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
Have tried several different ways, including "addEventListener". Nothing seems to work.
If you take a look at a minimal example you'll see that this also runs as soon as the page is loaded. Here setInterval() is called when the script loads in the page. In turn the run() function is called every second.
var timerID = setInterval(run, 1000);
function run() {
console.log("I'm running");
}
Think of the difference between var timer = run; and var timer = run(). The first assigns the function run to timer. The later executes run() and assigns the return value.
Here's your code with comments:
var sec = 5;
// start interval timer and assign the return value "intervalID" to time
var time = setInterval(myTimer, 1000);
// to be called every second
function myTimer() {
// assign an onclick handler to "b1" EVERY SECOND!
document.getElementById("b1").onclick = function() {
myTimer()
};
// update the demo DOM element with sec
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(time);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
For a solution I've moved setInterval into the onclick handler and moved said handler assignment out of the myTimer function as you only want to setup your handlers once.
I've also renamed time to timerID to make it clear what it is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button id="b1">Click Me!</button>
<p id="demo"></p>
<script>
var sec = 5;
var timerID;
document.getElementById("b1").onclick = function() {
timerID = setInterval(myTimer, 1000);
};
function myTimer() {
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(timerID);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
</script>
</body>
</html>
I would suggest a couple of extra exercises to help you:
Reset the timer so that you can click on the button to start the timer again
Prevent the timer being started again (which would run multiple timers with different IDs) while a timer is running
The myTimer() function is never invoked. Even if you invoke it, it does not take any action. It's just repeating itself on click.
So, instead of:
function myTimer() {
document.getElementById("b1").onclick = function() {
myTimer()
};
Try adding an Event Listener:
document.getElementById("b1").addEventListener('click', function() {
// inside here you put the code for going into next question
})
Or use just the same code, but not inside a function, and its content to be a meaningful code that leads to the next answer:
document.getElementById("b1").onclick = function() {
// code to proceed into next question
}
Related
I'm to write a function, such that when the Start Timer button is clicked, the h1 text counts down from 10 to 0. So, when the button is clicked, after 1 second, the text changes to 9, then after another second, it changes to 8, then 7, then 6, and so on, and the timer stops at 0. Additionally, when the countdown timer starts, the button is disabled, then when the timer elapses at 0, enable the button again.
I have written some code below but I don't know what I'm not doing right.
My code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>10</h1>
<button onclick='execute()'>Start Timer</button>
</body>
<script>
let count = document.getElementsByTagName("h1")[0].innerHTML;
setInterval(function execute() {
count--
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
btn = document.getElementsByTagName("button")[0];
if(count <= 0){
btn.disabled = true;
}
}, 1000);
</script>
</html>
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
setTimeout() is not a loop method
if you want to make a loop using setTimeout() :
setTimeout(function execute() {
count--
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
btn = document.getElementsByTagName("button")[0];
if(count <= 0){
btn.disabled = true;
}
else{
execute() // <- call your function again
}
}, 1000);
I am trying to display the alert message when the countdown is complete, I am trying the following code but its does not work please help!
<!DOCTYPE html>
<html>
<body>
<p id=count></p>
<form>
<button id="autoClickBtn" onclick="autoClick()">Click me</button>
</form>
<script>
function autoClick(){alert("I am loaded and automatically clicked");}
var count = 5;
var interval = setInterval(function () {
document.getElementById('count').innerHTML = count;
count--;
if (count === -1) {
clearInterval(interval);
window.onload = function () { document.getElementById("autoClickBtn").click() };
}
}, 1000 );
</script>
</body>
</html>
If you want to alert once after a certain time. Use setTimeout function. You can add the delay in milliseconds. In the example below I have added a delay of 2 secs.
setInterval, on the other hand, will run indefinitely again and again after time period defined
setTimeout(function () {
window.alert('This is an alert');
}, 2000);
I have two JavaScript "onload" functions that I am trying to run on a webpage: a visual timer and a auto refresh function. I have implemented both in my webpage but although the timer runs, the Auto Refresh function will not run unless I remove the visual timer function from the script.
Here is the code for the webpage:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body onload="JavaScript:timedRefresh(15000); timedText();">
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
Any help in solving this problem would be greatly appreciated.
try with a small change:call timedRefresh() inside window.onload's timetext() function not in body onload.
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
timedRefresh(15000);
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
The problem is the second one overrides the first. That is what you should be using addEventListener to add events.
window.addEventListener('load', timedText, false);
window.addEventListener('load', function(){timedRefresh(15000);}, false);
and if you need to support older IEs you need to look at attachEvent
BUT looking at the code why are you running two setTimeouts when all you need to do is when it hits zero call the redirect.
You can add multiple onload events using the addEventListener method, like so:
window.addEventListener("load", timedText, false);
window.addEventListener("load", timedRefresh(15000), false);
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if (counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",
timeoutPeriod);
}
You can find out more information about addEventListener here.
Here's a working codepen.
I really need some help with my Javascript countdown timer.
I am trying to make a countdown timer, for a quiz game, that resets and starts over when a button is pressed.
I can get it to reset and start over but if I press the button before time gets to 0, it will count down super fast.
Can anyone help? Here's the code:
<script type="text/javascript">
var countdown;
var time;
function init() {
time = 11;
reset();
trigger();
}
function trigger() {
if(time > 0) {
time--;
document.getElementById('timer').innerHTML = time;
if(time > 0) {
countdown = setTimeout('trigger()', 1000);
}
}
}
function reset() {
clearTimeout(trigger);
}
</script>
<input type="button" value="Reset" onclick="init()" />
<h3 id="timer">10</h3>
Of course I have the basic HTML document set up. The script is inside the tags and there's no difference in timer behavior if I place the script in element.
Thank you in advance!
You're not clearing the timeout in the reset. it should be
clearTimeout(countdown);
like this fiddle
I'm using Keith Wood's jQuery Countdown timer. http://keith-wood.name/countdown.html
What I want to achieve is a countup with stop and resume buttons, and controls to add and subtract minutes and seconds:
I create a countup (from 0 to 60 minutes) and pause it right away, like this:
$('#contador_tiempo').countdown({
since: 0,
format: 'MS',
layout: '{mnn}{sep}{snn}'
});
$('#contador_tiempo').countdown('pause');
But it seems that it's still running in the background. When I click the buttons to add or subtract, the functions do the operations on top of that background counter, not the displayed counter.
Full code on JSFiddle, with the behaviour reproduced:
http://jsfiddle.net/J2XHm/4/
(Play a bit with the controls and you will see that it keeps counting although it's paused.)
Yes, there is a bug in the 'getTimes' command - it recalculates when paused. I'll make the correction in the next release (1.6.2) but in the meantime you can change the _getTimesPlugin function:
_getTimesPlugin: function(target) {
var inst = $.data(target, this.propertyName);
return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()))));
},
If you can accept lightweight code, i.e. without using the jQuery countdown timer, the following might help you:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://localhost/web/JavaScript/jQuery/jquery"></script>
<script type="text/javascript">
var countUpSeconds = 0;
var interval = null;
function displayTime() {
$("#timeContainer").text(format(Math.floor(countUpSeconds/60))+":"+format(countUpSeconds%60));
}
function playStop() {
if(interval) {interval=window.clearInterval(interval);}
else {interval = window.setInterval(countUp, 1000);}
}
function countUp() {
++countUpSeconds;
if(countUpSeconds >= 3600) {/* do something when countup is reached*/}
displayTime();
}
function format(s) {return s<10 ? "0"+s : s;}
$(function() {
displayTime();
$("#playStop").on("click", function () { playStop(); } );
$("#addMin").on("click", function () { countUpSeconds += 60; displayTime(); } );
$("#subMin").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-60); displayTime(); } );
$("#addSec").on("click", function () { countUpSeconds += 1; displayTime(); } );
$("#subSec").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-1); displayTime(); } );
});
</script>
</head>
<body>
<div id="timeContainer"></div>
<button id="playStop">Play/Stop</button>
<button id="addMin">+1 minute</button>
<button id="subMin">-1 minute</button>
<button id="addSec">+1 second</button>
<button id="subSec">-1 second</button>
</body>
</html>