Slow down, console. (javascript/jquery) - javascript

I'm working on a console game and I don't like the speed at which the console.logs and how little time there is in between prompts and such. Is there a javascript/jquery method to slow down the game? To that effect, can I simply delay() every line (which sounds tedious), or if I were to use setTimeout(), would I theoretically have to split my game into a lot of different functions and set timeouts or intervals? What are your suggestions?
snippet for example:
alert('~~ WELCOME TO [x] ~~');
console.log('Before we get started, let\'s find out a little about you.');
var usr = {
name : prompt('What\'s your name?'),
age : prompt('How old are you?'),
clr : prompt('What\'s your favorite color?'),
pref : prompt('Which [x] is your favorite?'),
}
console.log('The air smells pungent today, and the weather is perfect.');
console.log(''); console.log('');
console.log('Did you hear that? I think something may be following us down the path to the [x]...');
console.log('');
var alpha = prompt('');
There will be if/elses, switches, all sorts of functions and choices. But I want the feel of a text-based console game.
I plan on adding a lot of different routes, features, and hopefully movement at some point. But that's all beside the point. If anyone knows a way or two to slow down a game that would follow this guideline, post any suggestion.

Most users consider prompts to be annoying and ugly. A user won't be able to interact with anything else including other tabs or console during the execution of prompts. Moreover, it is very inconvenient to work with it as a developer, because they are not configurable and they are hard in development, support and, especially, debugging.
It is a better idea to implement an HTML page which will interace with a user. So, you will be able to customize it and look nice.
For example, you can create a page which looks like chat - text window and input at the bottom. Like this:
function tell(text)
{
$("<p/>").text(text).appendTo($('#chat'));
}
function ask(text, callback)
{
$("<p/>").text(text).addClass('question').appendTo($('#chat'));
$('#send')
.prop('disabled', false)
.one('click', function() {
var text = $("#message").val();
callback(text);
$("#message").val("");
$(this).prop('disabled', true);
});
}
tell("Hi");
ask("What is your name?", function(x) {
tell("So strange...my name is " + x + ", as well...");
});
#chat {
padding: 20px;
position: absolute;
top: 0px;
bottom: 20px;
left: 0px;
right: 0px;
background-color: #DDDDDD;
}
#message {
position: absolute;
bottom: 0px;
left: 0px;
height: 14px;
width: 80%;
}
#send {
position: absolute;
bottom: 0px;
left: 80%;
width: 20%;
height: 20px;
}
.question {
font-weight: bold;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat"></div>
<input type="text" id="message"/>
<input type="submit" id="send" disabled/>
It is just an example. You may add any things like delays or CSS styling.

Create your own console, alert and prompt methods wrapping the natives.
For instance:
function logConsole(text, delay) {
window.setTimeout(function() {
console.log(text);
}, delay || 0);
};
You can change the 0 value in above to be a default delay if no delay argument is passed in.
logConsole('The air smells pungent today, and the weather is perfect.', 1000);
Just an idea

Related

Why does website cause most elements to be recalculated upon small change after being hosted?

I decided to make a Pac-Man game and after I did it and everything was working somewhat fine on local document I pushed my website on Github pages and decrease in fps was enormous. It turned out page was making recalculation for hundreds elements which caused 20ms+ delay.
Here's a small part of the code that still has performance difference between local and github-pages hosted website.
const gameBoard = document.getElementById("game-board");
const root = document.documentElement.style;
let elements;
let characterNode;
let position = 658;
makeLevel();
function makeLevel() {
for (let i = 0; i < 868; i++) {
const element = document.createElement("DIV");
element.style.backgroundPosition = `0 0`;
let character = document.createElement("DIV");
character.className = "yellow";
element.append(character);
gameBoard.append(element);
}
elements = Array.from(gameBoard.children);
characterNode = elements[658].children[0];
changePosition();
}
function changePosition() {
root.setProperty(`--yellow-sprite-y`, `-32px`);
characterNode.style.transform = `translateX(-20px)`;
setTimeout(() => {
characterNode.style.transform = "";
characterNode.classList.remove(`yellow-visible`);
position = position - 1;
characterNode = elements[position].children[0];
characterNode.classList.add(`yellow-visible`);
changePosition()
}, 200)
}
:root {
--yellow-sprite-y: -32px;
}
#game-board {
width: 560px;
height: 620px;
display: grid;
grid-template-columns: repeat(28, 20px);
background-color: #000000;
}
#game-board > * {
position: relative;
width: 20px;
height: 20px;
}
.yellow {
position: absolute;
top: -4px;
left: -5.5px;
width: 30px;
height: 28px;
z-index: 10;
}
.yellow-visible {
background-image: url("https://i.imgur.com/SphNpH6.png");
background-position: -32px var(--yellow-sprite-y);
transition: transform 200ms linear;
}
<div id="game-board">
</div>
The exact problem in this code is line 29 which on local document performs like this:
while after hosting it on Github performs this way:
Why is it working this way and what can I do to lessen the performance decrease on hosted page?
Amazingly everything works well and bug doesn't exist on CodePen, yet on Github it still persists.
After getting some feedback that my site works well for other users I shared it on CodePen and it also worked fine, day later somebody said there could be an extension that could do something like that and indeed Adblocker Ultimate caused the slow performance.

Problems with CSS changes in JavaScript

I am trying do a CSS change via JavaScript. I have a quiz site where, when the user marks the correct option, the option will become green, and when the user marks the incorrect option, the option will become red, but I have to change the color and redirect the user for another page, but the CSS change is very slow and, at certain times, doesn't work. This is my code:
CSS:
.choice{
white-space: normal;
word-wrap: break-word;
margin: 20px;
width: calc(40% + 100px);
height: calc(10% + 10px);
border-style: solid;
border-color: rgba(0, 0, 0, 0.4);
border-radius: 7px;
background-color: rgba(255,255,255,0.6);
cursor: pointer;
font-size: 20px;
transition: 0.4s;
}
JS:
function sleep(ms) {
var d = new Date();
var d2 = null;
do { d2 = new Date(); }
while(d2-d < ms);
}
function govariable(page,variable,valor,id,color) {
document.getElementById(id).style.backgroundColor = color
sleep(3000)
window.location.replace(`${page}?${variable}=${valor}`)
}
When you change something in the DOM (in this case, your background color) JavaScript won't update your screen until the event it is processing has finished.
This is because JavaScript runs in only one thread - it can't be looping around and around and re-displaying your background colour at the same time! It needs to finish looping first.
Instead of trying to implement a "sleep" function that will never work well in a single-threaded javascript world, you should try using setTimeout().
function govariable(page,variable,valor,id,color) {
document.getElementById(id).style.backgroundColor = color
setTimeout(function() {
window.location.replace(`${page}?${variable}=${valor}`)
}, 3000);
}
Instead of looping around again and again until time is up, at a very simplistic level this does something more like setting an internal "wake-up alarm" inside the JavaScript engine, that in 3000 milliseconds will go off, and tell JavaScript to run the code inside it. In this case, to call window.location.redirect.

Jquery Traversing to the Array

take a time To look at this website http://www.thejewelrysource.net/ and stay for like 7 seconds in the bottom left corner there is a small pop up that will appear and disappear again I want to do something like that using Jquery.
I know I could use Slideup and SlideDown Method but the problem I am facing is that How could traverse to the Given data in an Array so that I will Pop up the Data One at a Time. I am using only Static Data. Thank you for your Help in Advance! may someone help me! Thank You So Much
I couldn't understand much from your description. By any chance is this what are you looking are?
I have used setTimeout and setInterval to simulate this and a closure variable to keep track of the next item to display.
$(document).ready(function() {
var $popup = $(".popup"),
aMessages = ["Hello", "This is alert", "Is this what are you look for?"],
counter = 0;
$(".popup").hide();
var interval = setInterval(showMessage, 3000);
function showMessage() {
var iMessageId = counter % aMessages.length;
$popup.text(aMessages[iMessageId]);
$popup.show();
counter++
setTimeout(hideMessage, 1000);
}
function hideMessage() {
$(".popup").fadeOut(100);
}
setTimeout(function() {
clearInterval(interval);
}, 10000);
});
.popup {
width: 200px;
height: 100px;
background-color: yellow;
border-radius: 50px;
padding: 20px;
position: fixed;
left: 10px;
bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="popup"></div>

Unfold animation on DIV with Oridomi (JS)

I'm using the Oridomi (oridomi.com) Javascript plugin to achieve a paper folding animation. Specifically, I would like to have a div unfold on page load (picture a book opening).
However I am having difficulty getting the unfold() method to work, despite being a method which can be called on with the plugin.
You can see from this example, that I can only get the div to fold back, rather than unfold from a folded state (in effect, I would like the animation to be reversed).
My javascript function -
(function(){ function init(){
var $domi = $('.unfold').oriDomi({ vPanels: 2, hPanels: 1, speed: 500, shading: false });
setTimeout(function(){
$domi.oriDomi('reveal', -90);
}, 600);}
document.addEventListener('DOMContentLoaded', init, false);
})();
And CSS -
.unfold {
font-family: "Abril Fatface", "Hoefler Text", Constantia, Palatino, Georgia, serif;
font-size: 4.5rem;
width: 25rem;
height: 10rem;
text-align: center;
line-height: 1;
color: #ff676d;
background-color: #6ac1ff;
padding: 2.5rem 0;
}
The documentation on http://oridomi.com is not very clear on how this can be implemented. Any help would be very much appreciated. Thanks
If the Oridomi does not supports reverse you have 2 options. One would be to know the END stare and domi.oriDomi('reveal', 0);. The other would be to reverse it first on a speed of 0 and then reveal at 0deg to unfold. Here is a fiddle with this:
http://jsfiddle.net/Av6cD/2/
(function fold() {
var $domi = $('.unfold').oriDomi({
vPanels: 2,
hPanels: 1,
speed: 500,
shading: false
});
$domi.oriDomi('reveal', -90);
setTimeout(function () {
$domi.oriDomi('reveal', 0);
}, 1000);
})();
Please note that even if this is a nice effect, oriDomi is making a really mess to your DOM. CSS shaders would be the way to go once they get proper support.

Internet Explorer render issue (simple JS timer - window.setTimeout)

<script language="JavaScript" type="text/javascript">
var theBar = createProgressBar(document.getElementById('progress-bar'));
var value;
function resetValue() {
value = 0;
}
function showProgress() {
value += 1;
theBar.setValue(value);
if (value < 100) {
window.setTimeout(showProgress, 100);
}
}
window.onload=resetValue();showProgress();
</script>
--
<script language="JavaScript" type="text/javascript">
function createProgressBar(elem) {
var div1 = document.createElement('DIV');
div1.className = 'progress-bar-background';
div1.style.height = elem.offsetHeight + 'px';
elem.appendChild(div1);
var div2 = document.createElement('DIV');
div2.className = 'progress-bar-complete';
div2.style.height = elem.offsetHeight + 'px';
div2.style.top = '-' + elem.offsetHeight + 'px';
elem.appendChild(div2);
return {
div1 : div1,
div2 : div2,
setValue : function(v) {
this.div2.style.width = v + '%';
}
}
}
</script>
--
div.field input{
height: 45px;
width: 270px;
font-size: 24px;
}
.progress-bar-background {
background-color: #D0D0D0;
width: 100%;
position: relative;
overflow:hidden;
top: 0;
left: 0;
}
.progress-bar-complete {
background-color: green;
width: 50%;
position: relative;
overflow:hidden;
top: -12px;
left: 0;
}
#progress-bar {
width: auto;
height: 10px;;
overflow:hidden;
border: 0px black solid;
}
--
This snippet works perfectly under Chromer, Safari and FireFox.
The only issue is with Internet Explorer.
It seems to render as "half-full" and doesn`t execute anything.
Since I`m not that familiar with JS I have no clue what to start looking for.
Would appreciate some noob friendly advice.
change this...
window.onload=resetValue();showProgress();
to this...
window.onload = function() {
createProgressBar();
resetValue();
showProgress();
};
and you should be fine.
Remember...
"window.onload" is a property of the Window object ... and the value of this property should be a function that will execute automatically once the browser has loaded the entire DOM AND all the content (images, css, js, etc.)
This a NOT a good place to execute your stuff however -- you should use the event "onContentLoaded" but since it is not uniformly supported across browsers -- you should use a JavaScript library such as jQuery or Prototype or MooTools instead.
BUT -- of course if you're new to JS -- do NOT skim over it in order to get the pleasure of using these libs -- first get the real taste of what JavaScript is and what it is like to juggle with the browser incompatibilities -- only then you'll be able to appreciate the full potential of these libraries.
The first thing I see is that you shouldn't create the progress bar (or reference anything in the DOM) until the page has been loaded. IE is particularly sensitive to this. It looks to me like you're calling createProgressBar right when the javascript is loaded rather than after the page is loaded.
When I put your stuff into a jsFiddle and make sure that the code doesn't run until the page is loaded, it works for me in IE8.
See it here: http://jsfiddle.net/jfriend00/CQqat/

Categories