I'm attempting with the following code to
Display the results of a card game,
Wait for 3 seconds while displaying a countdown and then,
Reload the screen.
//Display results, at least that was the idea.
for(var player = 0; player < players.length; player++)
{
resultString = players[player][6]
if (result == null) { resultString += ", its a tie."; }
else
{
resultString += (player == 0 ? ", you" : ", cassino") +
(player == result ? (player == 0 ? " win" : " wins") :
(player == 0 ? " lose" : " loses"));
document.getElementById(player == 0 ? "player" : "casino").
childNodes[0].nodeValue = resultString;
}
showHand(players[player]);
}
//Lag for 3 seconds while displaying a countdown. At least it lags alright.
var time = new Date().getTime();
while (((time / 1000) + 3) - (new Date().getTime() / 1000 ) > 0)
{
document.getElementById("call").childNodes[0].nodeValue = "Next round in "
+ Math.ceil(((time / 1000) + 3) - (new Date().getTime() / 1000 ))
.toFixed(0);
}
//Reload screen. Working fine.
dealHands();
}
The problem is that by running this code the screen instead freezes for 3 seconds before loading the reloading the screen, even though console.log points out no problems with the values to be displayed in the "//Display results" section of the program. In fact, if I comment the portion after the comment "//Lag for 3 seconds..." the results are displayed as intended.
Is there some property of .time() that I'm unaware of that is overriding the code?
If you want to display countdown after 3 seconds, you can put your code to reload the screen in a function and call that function using window.setTimeout which wouldn't freeze the window and function gets invoked after the amount of time you specify there.
And for the countdown display, you can use window.setInterval.
Related
I am trying to get my countdown to stop at zero however it resets rather than stops.
I've added a conditional statement at the end of the runTimer function but nothing happens. It just resets.
I'm going off of an exercise where it counts up. I'm modifying it a bit and having it countdown.
function runTimer() {
let currentTime = leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
theTimer.innerHTML = currentTime;
timer[3]--;
timer[0] = Math.floor((timer[3]/100)/60); //minutes
timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60)); //seconds
timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000)); //hundredths
if (currentTime = 0) {
clearInterval(interval);
}
}
I expected it to stop at zero but it just resets back to 59:00... and I want it to stop at 00:00.
The problem is this part:
if (currentTime = 0)
Since you're checking if the value is 0, you don't want to assign a value of 0, instead you want to compare currentTime with 0. This is done with the === operator. So to summarize:
= is to assign a value to a variable. ( left is variable and right is the assignment)
== or === is to compare the two values.(Difference between == and === in JavaScript)
Your line should be:
if (currentTime == 0)
Hope it helped. :)
Two points.
1) As already mentioned, your if clause will not work because you are using "=" (a single equal sign). A single equal sign in JavaScript does assign values, not compare values. You however want to compare values and need to use double or triple equals.
2) Even if you change that, currentTime will probably never evaluate to zero, since you have assigned a string to currentTime before. So even if currentTime is "00:00", the string will not evaluate to 0 (see image)
I guess you more want to do something like this:
if (timer[2] === 0 && timer [1] === 0 && timer[0] === 0) {
clearInterval(interval);
}
Or most probably this will suffice:
if (timer[3] <= 0) {
clearInterval(interval);
}
The game is WAR, or Get Your Neighbour, a traditional game utilising a standard deck of 52 cards, no jokers. Currently the code recognises when a card is above 10 and so the rules of the game are being followed, all that is great, I've designed a timer that takes the value of the card 2-14, subtracts 10, then uses that number for the round of turns the other player has to draw above 10 before you win. Still building the cooperative/multiplayer element but for now, I'd just like to get this bloody button working!
When I click it, it does nothing. Before, it would tell me that "'timerf' is not a function". I'm probably doing something very obvious like problems with the order that things are loaded/data is parsed, but I'm still learning so I'd appreciate any help! Any questions, let me know.
var card = null; // setem 160517
var timer = null; //
window.onload = function() {
function draw(min, max) { // draw a card between 2-14
card = document.getElementById("draw").innerHTML = Math.floor(Math.random()*((max - min)+1) + min); // min 2, max 14
if (card > 10) {
timer = card - 10;
timerf(timer);
} else if (card < 11 && timer > 0) {
timer = timerf(timer-1);
}
} // draw
//draw(2,14);
document.getElementById("clickMe").onclick = draw(2,14);
} // window.onload
function timerf(timer) { // print turns to win
if (timer > 0 && timer < 5 && timer != 1) { // print turns to win
console.log("you have " + timer + " turns to win!");
} else if (timer == 1) {
console.log("you have " + timer + " turn to win!");
}
}
<div id="draw"></div>
<button id="clickMe">WAR!</button>
The return value of the draw function is undefined because it has no return statement.
document.getElementById("clickMe").onclick = draw(2,14);
… so you are assigning undefined to the onclick property.
You have to assign the function you want to call.
So, I am going to actually kill two birds with one stone. First off, I am trying to trigger an alert once the slider moves left to a specific degree. For example, once it goes to, let’s say, the 3rd slide I would like for it to trigger an alert. Also, I need help with the cycling of the slider. I want the slider to cycle like a rotation (360), but instead at the end of the cycle it slides all the way back to the start. View the Codepen to have a better understanding of what I mean. Thank you for your time. Your help is much appreciated.
Live Codepen
var W = $('#image_rotator').width(),
N = $('#slider .slide').length,
C = 0,
intv;
if (N <= 1) $('#left, #right').hide();
$('#slider').width(W * N);
$('#left, #right').click(function() {
C = (this.id == 'right' ? ++C : --C) < 0 ? N - 1 : C % N;
$('#slider').stop().animate({
left: -C * W
}, 300);
});
function setResetInterval(e) {
var intv = $("#slider");
if (e) {
timer = setInterval(function() {
$('#right').click();
}, 1000);
} else {
clearInterval(timer);
}
$('#slider').click(function() {
var x = $('#slider').offset();
alert("Top: " + x.top + " Left: " + x.left);
});
}
$("#btn").click(function(e) {
e.preventDefault();
setResetInterval(true);
});
$("#btn2").click(function(e) {
e.preventDefault();
setResetInterval(false);
});
$('#slider').hover(function(e) {
return e.type == 'mouseenter' ? setResetInterval(false) : setResetInterval(true);
});
This accomplishes both of the things that you wanted using the optional callback parameter in the animate function. It checks first to see if the variable C (the 0-based index of the current slide) is equal to 2 (3 in 1-based indexing), and shows an alert if it is. Then it checks to see if C is equal to 10 (which would mean that the slide currently being shown is the 9th one; The 9th image is just a duplicate of the 1st one) If it is on the 9th one, then jump back to the first one and trigger $("#right").click();.
$('#left, #right').click(function() {
C = (this.id == 'right' ? ++C : --C) < 0 ? N - 1 : C % N;
$('#slider').stop().animate({
left: -C * W
}, 300, function() {
if (C == 2){alert("3rd");}
if (C == 10) {
$('#slider').css("left", "0");
$('#right').click();
}
});
});
JSFiddle (Because CodePen's layout is weird to me)
Below is the functions I use to run a function periodically. I use the function to change the background of the body. but it doesn't get fired for some reason. Please help me with this code.
setInterval(uiImageChanger(),1);
function uiImageChanger(){
var currentTime = new Date().getHours();
var images = ['image1.jpg','image2.jpg'];
if( currentTime > 00 && currentTime <= 12){
$('body').css('background-image', "url(" + randomImagePicker(images ,'breakfast') + ")");
}else if( currentTime > 12 && currentTime <= 16){
$('body').css('background-image', "url(" + randomImagePicker(images ,'lunch') + ")");
}else if( currentTime > 16 && currentTime <= 00){
$('body').css('background-image', "url(" + randomImagePicker(images ,'dinner') + ")");
}
}
function randomImagePicker(imgArray,time){
if(time == 'breakfast'){
return "../images/main_image/breakfast/" + imgArray[Math.floor(Math.random() * imgArray.length)];
}else if(time == 'lunch'){
return "../images/main_image/lunch/" + imgArray[Math.floor(Math.random() * imgArray.length)];
}else if(time == 'dinner'){
return "../images/main_image/dinner/" + imgArray[Math.floor(Math.random() * imgArray.length)];
}
}
Thank you.
Remove parens from the setInterval function argument. Now, this will invoke the function and set the return value of the function as the reference to setInterval which here is undefined as you don't return anything. So basically you are setting interval on nothing, so nothing happens except the first execution while setting up the setInterval.
Change
setInterval(uiImageChanger(),1); // This will invoke the function immediately.
to
setInterval(uiImageChanger,1); // You want to set the reference of the function to setInterval.
You have to pass a pointer to a function and not execute the function.
setInterval(uiImageChanger,1);
There are multiple ways of defining the function to be executed using setInterval.
One of the method is using the function reference for which the example is given by #mohkhan.
However you can do the following as well
setInterval(function(){
// code comes here.
}, time_in_mills);
Also I see that you have mentioned the value for the function execution as 1. This means every 1 millisecond the function will be executed, which is not a good practice at all. Give a realistic time in millisecond so that you have given sufficient time for the code to execute.
You've gotten several answers about the setInterval() problem. I'd like to point out a couple of other problems in the code.
First, this test will always fail:
else if( currentTime > 16 && currentTime <= 00)
After all, if a number is > 16 it cannot also be <= 0.
Also, you may get a warning about 00 being an octal constant which is deprecated. Of course, octal zero is the same value as decimal zero, but watch out for inadvertent octal constants: avoid using a leading zero.
And there is a lot of repetition in the code. You can easily remove all of this repetition to make the code more maintainable. Consider this approach:
// Return a random integer >= 0 and < n
function randomInt( n ) {
return Math.floor( Math.random() * n );
}
// Return a random element from an array
function randomElement( array ) {
return array[ randomInt(array.length) ];
}
function uiImageChanger(){
var hour = new Date().getHours();
var meal =
hour <= 12 ? 'breakfast' :
hour <= 16 ? 'lunch' :
'dinner';
var images = [ 'image1.jpg', 'image2.jpg' ];
$('body').css(
'background-image',
'url(../images/main_image/' + meal +
'/' + randomElement(images) + ')'
);
}
I'm trying to write a script for roulette system and I want the script to run until the bank variable reaches 0 or 11,000, and produce three pieces of data after each spin.
I have left parts of the code out for simplicity. The code in the if else statement is not the problem. Running the script until the variable reaches a certain point is where I'm stuck.
Would anyone be able to help me rewrite this script please? Thanks in advance.
(function() {
var bank = 10000;
var bet = 1;
function spin() {
var number = Math.floor(Math.random() * 36);
if ( number == 0 ) {
document.write("<p>The number " + number + " is neither high nor low.</p>");
// removed
}
else if ( number > 18 ) {
document.write("<p>The number " + number + " is a high number.</p>");
// removed
}
else {
document.write("<p>The number " + number + " is a low number.</p>");
// removed
}
};
spin();
document.write("<p>Total bank is now " + bank + ".</p>");
document.write("<p>The next bet is " + bet + ".</p>");
})();
If you're calling this loop within a page (i.e. you don't want the page to hang up for the duration, or want to display results) you should use requestAnimationFrame:
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
Then set up your loop to only call itself if the bank is within your accepted range:
function spinLoop() {
spin();
//perform your UI updates here
if (bank >= 0 && bank <= 11000) requestAnimFrame(spinLoop);
}
You will, of course, need to call this function initially to start the loop:
spinLoop();