I am busy making a Red Or blue clicking game which can be viewed here: http://www.ysk.co.za/red-blue
My problem is the countdown I have made by de incrementing var countdown only stops when the function key() is run, and until it is run the countdown goes into negative values if more than 12 seconds
My Javascript is:
var i = 0;
var seconds = 0;
var countdown = 12;
setInterval(function () {
$("#counter").html(countdown.toFixed(2));
}, 10);
function play() {
$("#num").select();
}
function key(e) {
var code = e.keyCode ? e.keyCode : e.charCode;
var random = Math.random();
if (random <= 0.5) {
$("#RedBlue").css("background-color", "red")
} else {
$("#RedBlue").css("background-color", "blue")
}
if (code === 86) {
$("#red").css("background", "#ff4e00");
setTimeout(function () {
$("#red").css("background-color", "red")
}, 500);
var color = "rgb(255, 0, 0)";
} else if (code === 66) {
$("#blue").css("background-color", "#006bff");
setTimeout(function () {
$("#blue").css("background-color", "blue")
}, 500);
color = "rgb(0, 0, 255)";
}
var score = i / seconds;
var Endscore = (i - 1) / seconds;
if ($("#RedBlue").css("background-color") != color) {
alert("You clicked " + i + " times in " + seconds.toFixed(2) + " seconds. your score was " + score.toFixed(2));
document.location.reload(true);
} else if ($("#RedBlue").css("background-color") == color) {
$("#score").html("");
i++;
}
if (i == 1) {
setInterval(function () {
seconds += 0.01
}, 10);
setInterval(function () {
countdown -= 0.01
}, 10);
};
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}
My HTML is:
<div id="game">
<div id="RedBlue"></div>
<div id="red" style="background:red;"></div>
<div id="blue" style="background:blue;"></div><div class="clear"></div>
<button onclick="play()">start</button><br>Enter "v" if the block is red or "b" if the block is blue
<input type="text" size="2" maxlength="1" id="num" onkeyup="key(event); this.select()" />
</div>
<div id="counter" style="font-family:monospace;font-size:100px;font- weight:600;float:left;margin-left:40px;"></div>
<div id="score"></div>`
How Can I do this so that when countdown == 1 the alert() appears, also if you know of any better way to stop and reset the game other than refreshing the page that would be great.
Your help is much appreciated
Since you are updating your time in the setInterval, you should check in there whether the countdown value has reached 0
setInterval(function () {
countdown -= 0.01;
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}, 10);
Related
Iam trying to give 2 different colors on my timer countdown apps..
on workout timer will be green.
on rest timer will be red. (and the color will be red until end)
my question is how to make the timer back to green after rest timer(red) and back to red after green(workout timer)
document.getElementById('start').addEventListener('click', startCountdown);
function startCountdown() {
let counter = 3,
mode = "Workout",
rounds = 1;
const interval = setInterval(function() {
counter--;
if (mode == "Workout" && counter >= 0) {
id = document.getElementById("count");
id.innerHTML = "ROUND " + rounds + " <br> " + counter;
id.classList.add('green') <<<THE FRIST COLOR RUNNING WELL
} else {
id = document.getElementById("count");
id.innerHTML = "REST " + " <br> " + counter;
id.classList.add('red') <<< SECOND COLOR RUNNING WELL
}
if (counter === 0) {
if (mode == "Workout") {
mode = "Rest";
} else {
mode = "Workout";
rounds++;
}
id.innerHTML = "DONE";
counter = 3;
if (rounds == 21) {
clearInterval(interval);
}
}
}, 1000);
add this near line 9
(mode == "Workout" && counter >= 0) ? clsnm="green" : clsnm="red";
and pass this variable near id.classList.add(clsnm)
alternatively you can also try to add id.classList.remove('class_name') before id.classList.add('class_name')
I'm trying to get this to look nice. This countdown is meant to go negative, once it does I'd like the skull and crossbones to be visible, and I'd want it to flash. I'm using this Javascript functionality...
var img = document.getElementById('Image1');
var interval = window.setInterval(function() {
if (img.display == 'hidden'){
img.style.visibility = 'visible';
} else {
img.style.visibility = 'hidden';
}
}, 1000);
Once it's flashing, how do I get it to overlap the countdown span?
http://jsfiddle.net/2Lufxs2t/3/
After var img = document.getElementById('Image1'); add document.getElementById('countdown').style.display='none'; to hide your counter.
Remove your second interval: var interval = window.setInterval(function(){. Just leave the if that toggles the visibility as it is. The problem is that secondPassed() is running every second, and then your second interval is running again every second. So every second your inner interval runs twice and toggles itself.
JSFiddle This worked great for me.
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
var seconds = 10;
function stopTimer() {
clearTimeout(countdownTimer)
}
function floor(x) {
return x | 0;
}
function pad(n) {
if (n < 0) {
n = -n;
}
if (n < 10) {
return '0' + n.toString();
}
return n.toString();
}
function secondPassed() {
var minutes = pad(floor(seconds / 60));
if (seconds < 0) {
minutes = '-' + minutes;
}
var remainingSeconds = pad(seconds % 60);
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds > 0) {
seconds--;
if (seconds > 8) {
document.body.style.backgroundColor = "green";
} else if (seconds == 5) {
document.body.style.backgroundColor = "yellow";
} else if (minutes == 0 & seconds == 0) {
document.body.style.backgroundColor = "red";
if (seconds%2 == 0) {
document.getElementById('skull').style.display="none";
}
if (seconds%2 != 0) {
document.getElementById('skull').style.display="block";
}
}
} else {
if (seconds%2 == 0) {
document.getElementById('skull').style.display="block";
}
if (seconds%2 != 0) {
document.getElementById('skull').style.display="none";
}
seconds--;
}
}
</script>
</head>
<body>
<img id="skull" src="http://s15.postimg.org/es5w3xpob/skull.gif"style="position:absolute; z-index: -1;display:none;">
<div style=" z-index:10;">
<p align ="center">
<span id="countdown" style="color:black; font-size: 450px; font-weight: bold;" ></span>
</br>
<button onclick="countdownTimer = setInterval('secondPassed()', 1000)">Start</button>
<button onclick="stopTimer()">Stop</button>
</p>
</div>
</body>
</html>
I am trying to create a countdown timer that counts down from an hour if a user enters 1 or 2 hours if a user enters 2, etc.. I know I need to multiply the value I am getting from the user by 60 in order to switch from calculating minutes and seconds from the input to calculating by hour but I am just not quite sure where to do so.
<script>
function startTimer() {
userInput = document.getElementById('userTime').value;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if(!userInput.match(numericExpression)){
alert("Please enter a number")
} else {
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () { display("notifier", "Warning message 1", document.bgColor="#ffff00"); },
5: function () { display("notifier", "Warning message 2", document.bgColor="#ff69b4"); },
0: function () { display("notifier", "Final message", document.bgColor="#ff0000"); }
});
}
}
}
</script>
<div id="countdown"></div>
<div id="notifier"></div>
<p>
Please Enter A Time Limit for the Meeting: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="startTimer()" />
</p>
All you really need to change is your toMinuteAndSecond function, which I have renamed and done below:
userInput = document.getElementById('userTime').value;
if (userInput.length == 0) {
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if (!userInput.match(numericExpression)) {
alert("Please enter a number")
} else {
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toFormattedHHMMSS(x) {
var hours = parseInt(x / 3600);
var minutes = parseInt(x / 60) % 60;
var seconds = x % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
}
function setTimer(remain, actions) {
(function countdown() {
display("countdown", toFormattedHHMMSS(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () {
display("notifier", "Warning message 1", document.bgColor = "#ffff00");
},
5: function () {
display("notifier", "Warning message 2", document.bgColor = "#ff69b4");
},
0: function () {
display("notifier", "Final message", document.bgColor = "#ff0000");
}
});
}
}
The same would be done for allowing days, or weeks, etc...
seems like allot more code than needed to simply count down. Of course I don't know the broader aspects of your implementation but nonetheless I'm a big fan of getting to the point and reducing the complexity of code.
A simple start point is that you can reduce all of this:
if (userInput.length == 0) {
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if (!userInput.match(numericExpression)) {
alert("Please enter a number")
} else {
to this:
if ((+userInput > 0) !== true) {alert("Please enter a valid time"); return;}
And here's an example of cutting the whole thing back:
<script>
function startTimer() {
var t = document.getElementById('userTime').value;
if ((+t > 0) !== true) {alert("Please enter a valid time in hours"); return;}
t = parseFloat(t, 10) * 3600; //convert hours & fractions of hours to seconds
countDown(t);
}
function countDown(t) {
if ((t - 1) > 0) setTimeout(function(){countDown(t - 1); }, 1000);
printTime(t-1);
}
function printTime(t) {
var e = document.getElementById("countdown");
e.innerHTML = (t == 0) ? "Times up!" : Math.floor(t / 60) + ":" + t % 60;
e.style.color = (t < 300) ? "#ff0" : (t < 600) ? "#ff69b4" : "#000";
}
</script>
Now to build in better formatting, more user messages, warnings etc you only need to work on the printTime(t) function.
http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/
To create a ticking movement and not a sliding one of a number on a canvas i want to move the number up in 0,2 secondes and wait 0,8 seconds. The codes works good for a sliding movement but to implement the ticking i get lost.
jsfiddle
var ittt = 0;
var add = null;
function MinuteTimer() {
add = setInterval(function () {
totime();
if (ittt % (40 * 60) == 0) {
ittt = 0;
}
}, 5);
};
function stoptimer() {
clearInterval(add);
};
function totime() {
drawcanvasbackground();
drawnumberscanvas(ittt);
ittt += 1;
if (ittt % 40 == 0 && ittt > 0) {
clearInterval(add);
setTimeout(MinuteTimer(), 800);
};
};