struggling with Displaying Timer - javascript

Hi all I found a useful bit of JS here:
http://jsfiddle.net/4tj6r/2/
and I am trying to run this as follows but, for some reason I am receiving no output on the webpage - I am a complete newbie so if this is simple many apologies but if there is anyone kind enough out there please point me in the right direction - the code is as follows:
<script type="text/javascript">
$(function() {
var count = localStorage.getItem('count') || 20,
countdown = setInterval(function() {
localStorage.setItem('count', count);
$("p.countdown").html(count + " seconds remaining!");
if (count == 0) {
clearInterval(countdown);
localStorage.removeItem('count');
window.location = 'http://stackoverflow.com/';
}
count--;
}, 1000);
});
</script>
<p class="countdown"></p>
many thanks in advance

All you miss is to call the jQuery library
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function() {
var count = localStorage.getItem('count') || 20;
var countdown;
countdown = setInterval(function() {
--count;
if(count>0){
localStorage.setItem('count', count);
$("p.countdown").html(count + " seconds remaining!");
}else{
clearInterval(countdown);
localStorage.removeItem('count');
window.location = 'http://stackoverflow.com/';
}
}, 1000);
});
</script>
<p class="countdown"></p>

Related

JavaScript timer for a quiz

I am making a quiz game for a project in HTML and JavaScript. On every question, the player has 15 seconds to answer. I managed to do it like this:
<body onload="setTimeout(Timer,15000)">
and then in Js:
function Timer()
{
alert("You are out of time!");
}
However, I want to be able to display how much time the player has left in a <p> tag. How could I do that?
<div id="count">Start</div>
var count = 15;
var interval = setInterval(function(){
document.getElementById('count').innerHTML=count;
count--;
if (count === 0){
clearInterval(interval);
document.getElementById('count').innerHTML='Done';
// or...
alert("You're out of time!");
}
}, 1000);
Here's a basic example of a countdown timer
var count = 15;
var timer = setInterval(function() {
console.log(count);
count--;
if(count === 0) {
stopInterval()
}
}, 1000);
var stopInterval = function() {
console.log('time is up!');
clearInterval(timer);
}
Repl: https://repl.it/I2C6
Initialize the variable 'sec' with timeout time in seconds.
Call setInterval() which has 2 parameters, 1st is the method name and 2nd parameter is interval between invoking the method mentioned in 1st parameter.
var sec = 15;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById('timer').innerHTML = sec + "sec left";
sec--;
if (sec == -1) {
clearInterval(time);
alert("Time out!! :(");
}
}
Time : <span id="timer"></span>

countdown timer reset on each page

i have an exam system in php on which i have set a countdown timer with the help of javascript. the questions are displayed one by one on the page and the timer reset to the initial position when the next question comes also the page refreshes itself. I want to set the timer on the decreasing state so is should not start again and again to the initial time. the code is the following i have written for the timer. please anyone help me to sort it out.
<div id="test_time">
<script language="javascript" type="text/javascript">
var min = 10;
var sec = 0;
var timer;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = "Time Left : Minutes: " + min + " Seconds: " + sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : Minutes: 0 Seconds: 0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
</script>
</div>
First you must understand the concept of Jquery while working with the countdown timer and Quiz like PHP project.
You have to follow the following process in the System:
You have to load the question in AJAX.
You must have the div which loads the timer at the page load after the login is being done.
The timer div must not be loaded since the jquery will be keep loading if the page reloads again.
Only once the page has to be loaded that is after the login is done and after that the page should not be loaded and it has to changed inly with the help of AJAX.
Since if the question is loaded over the AJAX only the question div alone will be loaded and that to with AJAX and all the other part of the page will remain the same and you can maintain the timer in a correct manner.
Hope so you might be clear with the Explanations.
Happy Coding :)
Well , the above answer is the proper approach to the problem but still if you want it to work as it is, then you can prefer local Storage Variables.
Let this be home.php
<div id="test_time">
<script type="text/javascript">
var timer;
localStorage.min=10;
localStorage.sec=10;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = "Time Left : minutes: " + localStorage.min + " seconds: " + localStorage.sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : minutes: 0 seconds: 0") {
if (localStorage.sec == 0) {
localStorage.min = localStorage.min - 1;
localStorage.sec = 59;
} else {
localStorage.sec = localStorage.sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
ActivateTimer();
</script>
</div>
<div>
Next Question
</div>
Let this be next_question_1.php
<div id="test_time">
<script type="text/javascript">
function Timer() {
var _time = "Time Left : minutes: " + localStorage.min + " seconds: " + localStorage.sec;
document.getElementById("test_time").innerHTML =_time;
if (_time != "Time Left : minutes: 0 seconds: 0") {
if (localStorage.sec == 0) {
localStorage.min = localStorage.min - 1;
localStorage.sec = 59;
} else {
localStorage.sec = localStorage.sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
alert('Test Time Over.. Click Ok to get Results.');
window.location = "result.php";
}
}
Timer();
</script>
</div>
<div>
<a href="next_question_2.php">Next Question
</div>
Since they are local Storage variables they carry on to next pages until you clear the cookies, you may add as many pages you want. This solves your problem but, I don't recommend such approach. AJAX is the proper way to do it. :)

Javascript setTimeout function with JQuery

I'm new to JQuery and Javascript, I try to write a small setTimeout function but it seems not to work. Below is my code, can some one help out by pointing out what is wrong here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="/jquery-2.1.4.js"></script>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
}, 1000);
});
</script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<button type="button" id="submit" value="send"></button>
</body>
</html>
Your code executes on .click on the submit button - which means it only executes when you click the button. Also using setTimeout you are only running it once, and by the inner logic of the function it seems you want it to be ongoing. Substitute setTimeout to setInterval to keep it running.
`$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setInterval(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
$('#input').val(minute + ':' + second);
}, 1000);
});`
have to recursive to make call and call again....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<input type="button" id="submit" value="send"></input>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
rece();
function rece(){
if (minute == 0 && second == 0) {
alert("no time left");
console.log('no time left')
}
else if (second !== 0) {
second--;
console.log('second');
rece();
}
else {
minute--;
second = 60;
console.log('minute');
rece();
}
second--;
}
}, 100);
});
</script>
</body>
</html>
I've modified your code slightly and created a fiddle: JsFiddle
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
$('#input').val(minute + ':' + second);
}, 1000);
});

increment value of a number with a specific timer-value

I've tried and looked around but I could not find anything similar.
<div> <span>23</span>/ 30 </div>
My thought process here is that I want 23 to increment in 1 value every 15th second.
And when it hits 30, it shall stop counting. I have no idea how to make it "stop" counting and how I should approach a problem like this.
Any help would be much appreciated!
Here is a possible solution, note that I do an iteration every second for the demo, but you can lower the rate by doing setTimeout(count,15000);.
var wrapper, value, timer;
window.addEventListener('load', startCounter, false);
function startCounter(){
document.querySelector('button').onclick = startCounter;
wrapper = document.querySelector('span');
value = 22;
count();
}
function count(){
clearTimeout(timer);
value++;
wrapper.innerHTML = value;
if(value < 30){ timer = setTimeout(count,1000); }
}
<div> <span>23</span>/ 30 </div>
<button>reset</button>
<div id="show"></div>
<script>
function timer(){
var i = 0;
setInterval(function(){
i++;
document.getElementById("show").innerHTML = i;
if(i > 30){
i = 0;
}
},1000);
}
timer();
</script>
//just super simple hope can be inspiration done thank
If a class is added to the span element like so:
<div> <span class="counter">23</span>/ 30 </div>
Then this javascript code would work:
var currentCount = parseInt($('.counter').text());
var increaseCount = function() {
if (currentCount < 30) {
currentCount = currentCount + 1;
$('.counter').text(currentCount);
setTimeout(increaseCount, 15000);
}
return;
};
setTimeout(increaseCount, 15000);
Here is an example with the timer set to a second:
https://jsfiddle.net/aqe43oLa/1/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var i = 24;
var timer=setInterval( increment, 15000);
function increment(){
if(i<=30)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
else
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div><span class="increase">23</span>/ 30 </div>
</body>
</html>

How to stop timer after ten seconds in javascript using setInterval and clearInterval?

I was wondering how can I stop a timer after ten seconds in javascript using setInterval and clearInterval??
Here's my code example, could you please tell me where I'm going wrong:
<!DOCTYPE html>
<html>
<head>
<script>
var tt=setInterval(function(){startTime()},1000);
function startTime()
{
var today = new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
today=checkTime(today);
document.getElementById('txt').innerHTML=s;
}
function checkTime(tt)
{
if (tt==10)
{
tt="0" + tt;
console.log(tt);
clearInterval(tt);
}
return tt;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
you can set timeout on clear like this right after you set the interval:
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
Since startTime() will run every second, make a counter to increment to 10 inside of it, then clear the interval.
var tt=setInterval(function(){startTime()},1000);
var counter = 1;
function startTime()
{
if(counter == 10) {
clearInterval(tt);
} else {
counter++;
}
document.getElementById('txt').innerHTML= counter;
}
JSFiddle
Because you named a local variable named tt which does not let you access the global variable tt. Very bad planning on variable names.
Your code also will not stop at 10 seconds, it will stop when the time is at 10 seconds or 10 minutes.
function checkTime(xtt)
{
if (xtt==10)
{
xtt="0" + xtt;
console.log(xtt);
clearInterval(tt);
}
return xtt;
}
This works for me.
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
you can do that
setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));

Categories

Resources