For-loop not working till the specified input - javascript

The loop in myFunctionlp, is not working to the specified user input through prompt which is round in this case. I want that loop to run until the input of the user which I am getting through prompt. myFunctionlp is being called by a button press.
var round = prompt("Enter number of rounds");
var defaultNumberOfRounds = 1;
var roundno = isNaN(Number(round)) ? defaultNumberOfRounds : round;
var images_arr = ["../img/paper.png", "../img/stone.png",
"../img/sisor.png"
];
var size = images_arr.length;
console.log(`round: ${round}, roundno: ${roundno}`);
function myFunctionlp() {
for (var i = 0; i < roundno; i++) { //this loop
console.log(i);
setInterval(function() {
var x = Math.floor(size * Math.random())
$('#random').attr('src', images_arr[x]); // JQuery
}, 1500);
setInterval(function() {
var sound = new Audio("../audio/audio.mp3");
sound.play();
if (s == 50) {
sound.pause();
} else {
alert("Hello");
}
}, 3000);
}
}
function stop() {
for (s = 0; s < 51; s++) {
console.log(s);
}
}
function extra() {
var music = new Audio("../audio/audio_3.mp3");
music.play();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="onClick" onclick="myFunctionlp()">Play</button>

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

javascript function delay or set time out not working

i am trying to code the typed jquery functinality in javascript.I am almost there.HEre i need to add a delay after loading the word.like a few secons(lest say 4 sec) after each word loaded. How can i do it. In tried delay and set time out.It is not working for me or i am placing in wrong position. How can i set it.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
setInterval(function() {
var interval = setInterval(function() {
document.getElementById('p1').innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 >= arr[count].length) {
dir = false;
}
} else {
count2--;
if (count2 < 0) {
dir = true;
clearInterval(interval);
}
}
}, 100);
count++;
if (count == 6) count = 0;
}, 2500);
<div style="width=100%">
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
Your implementation will have problems if you add “A very long string” in to the array.
I’ve modified your code, hope it will help.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
var p1 = document.getElementById("p1");
// Turning the intervals to on or off.
var onOff = function(bool, func, time) {
if (bool === true) {
interval = setInterval(func, time);
} else {
clearInterval(interval);
}
};
var eraseCharacters = function() {
// How long we want to wait before typing.
var wait = 1000;
// How fast we want to erase.
var erasingSpeed = 100;
var erase = function() {
p1.innerHTML = arr[count].substring(0, count2);
count2--;
if (count2 < 0) {
dir = true;
// Stop erasing.
onOff(false);
count++;
if (count === 6) {
count = 0;
}
// Start typing.
setTimeout(startTyping, wait);
}
};
// Start erasing.
onOff(true, erase, erasingSpeed);
};
var startTyping = function() {
// How long we want to wait before erasing.
var wait = 4000;
// How fast we want to type.
var typingSpeed = 100;
var type = function() {
p1.innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 > arr[count].length) {
dir = false;
// Stop typing.
onOff(false);
// Start erasing.
setTimeout(eraseCharacters, wait);
}
}
};
// Start typing.
onOff(true, type, typingSpeed);
};
// Start typing after 2 seconds.
setTimeout(startTyping, 2000);
<div style="width=100%">
<!-- Maybe it should be class. -->
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>

Converting jquery to javascript progress bar

Please help me convert this JQuery to Javascript progress bar script
var generateButton = document.getElementById("generate");
if (generateButton.addEventListener) {
generateButton.addEventListener("click", random, false);
}
else if (generateButton.attachEvent) {
generateButton.attachEvent('onclick', random);
}
function random(e) {
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
//TODO: left and right text handling
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
var num = Math.random();
var greetingString = num;
document.getElementById("rslt").innerText = greetingString;
}
Here is the Live version: http://jsfiddle.net/chjjK/9/
Pretty easy actually, use document.getElementsByClassName and a for loop to replace the each:
var bar = document.getElementsByClassName("bar");
for (var i = 0; i < bar.length; i++) {
var me = bar[i];
var perc = me.getAttribute("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.style.width = current_perc+'%';
}
me.innerHTML = ((current_perc)+'%');
}, 50);
}
}, 300);
Demo: http://jsfiddle.net/chjjK/13/

Timer doesn't work in boolean

I have a problem with my timer -
var myTimer = function () {
var d = Date.now();
// var t=d.toLocaleTimeString();
var timerSeconds = Math.round((od - d) / 1000);
document.getElementById("timer").innerHTML = "Time left for this tour:" + timerSeconds;
if (timerSeconds > 0) {
setTimeout(arguments.callee, 1000);
} else {
finTour();
}
};
myTimer();
it calls this function:
var finTour = function () {
deleteCartes();
randomCell();
od = Date.now() + 5000;
myTimer();
window.setTimeout(function () {
tourOfComp();
}, 5000)
var tourOfComp = function () {
for (var i = 0; i < 12; i++) {
if (document.getElementsByTagName("td")[i].style.backgroundColor == "aqua") {
document.getElementsByTagName("td")[i].firstChild.data = cartes[prochaineCarte++]
}
}
for (var j = 0; j < 12; j++) {
if (document.getElementsByTagName("td")[j].style.backgroundColor == "aqua")
document.getElementsByTagName("td")[j].style.backgroundColor = "";
}
for (var k = 0; k < 3; k++) {
tab[k].value = "";
}
od = Date.now() + timeFixe;
myTimer();
};
the problem is when I fix the time 20, it calls these two last function and the time is always 5 and never 20 it seems that it doesn`t renew the time, but only repeat this:
window.setTimeout(function ()
{
tourOfComp();
},5000)

Drawing more than 1 to canvas wont work?

I am trying to draw enemy ships to the canvas that will come from the right at a random x being the height of the canvas and a random y past the right side + 1000.
This works fine however I am trying to make it automated and the code runs run it just does not work on screen, only 1 is drawn? Any more info that you need just ask, It's really frying my brain I went line by line for around 3 hours and can't see an issue.
Before I added this code and just called one manually: http://www.taffatech.com/DarkOrbit.html
After I added this code for automatic: (it kinda looks like its overlapping)
http://www.taffatech.com/test.html
Globals:
var spawnInterval;
var totalEnemies = 0; //leave as is
var enemies = []; //array of enemy objects
var spawnRate = 2000; //every 2 seconds
var spawnAmount = 3; //amount of enemies spawned
Then my init() calls a startLoop:
function startLoop()
{
isPlaying = true;
Loop();
startSpawningEnemies();
}
function stopLoop()
{
isPlaying = false;
stopSpawningEnemies();
}
function Loop()
{
if (isPlaying == true)
{
Player1.draw();
requestAnimFrame(Loop);
drawAllEnemies();
}
then they use these functions:
function spawnEnemy(n) //total enemies starts at 0 and every-time you add to array
{
for (var x = 0; x < n; x++)
{
enemies[totalEnemies] = new Enemy();
totalEnemies++;
}
}
function drawAllEnemies()
{
ClearEnemyCanvas();
for(var i = 0; i < enemies.length; i++)
{
enemies[1].draw();
}
}
function startSpawningEnemies()
{
stopSpawningEnemies();
spawnInterval = setInterval(function() {spawnEnemy(spawnAmount);}, spawnRate); //this calls spawnEnemy every spawnRate
/////////spawn 'spawnAmount' enemies every 2 seconds
}
function stopSpawningEnemies()
{
clearInterval(
spawnInterval);
}
which in turn calls the Enemy class:
function Enemy() //Object
{
//////Your ships values
this.EnemyHullMax = 1000;
this.EnemyHull = 1000;
this.EnemyShieldMax = 1000;
this.EnemyShield = 347;
this.SpaceCrystalReward = 2684;
this.EnemySpeed = 2; //should be around 6 pixels every-time draw is called by interval, directly linked to the fps global variable
////////////
////Pick Ship
this.type = "Hover";
this.srcX = EnemySrcXPicker(this.type);
this.srcY = EnemySrcYPicker(this.type);
this.enemyWidth = EnemyWidthPicker(this.type);
this.enemyHeight = EnemyHeightPicker(this.type);
this.drawX = EnemydrawXPicker(this.type);
this.drawY = EnemydrawYPicker(this.type);
////
}
Enemy.prototype.draw = function()
{
this.drawX -= this.EnemySpeed;
ctxEnemy.globalAlpha=1;
ctxEnemy.drawImage(spriteImage,this.srcX,this.srcY,this.enemyWidth,this.enemyHeight,this.drawX,this.drawY,this.enemyWidth,this.enemyHeight);
}
function EnemySrcXPicker(type)
{
if (type == "Hover")
{
return 906;
}
}
function EnemySrcYPicker(type)
{
if (type == "Hover")
{
return 616;
}
}
function EnemydrawXPicker(type)
{
if (type == "Hover")
{
return Math.floor(Math.random() * 1000) + canvasWidthEnemy;
}
}
function EnemydrawYPicker(type)
{
if (type== "Hover")
{
return Math.floor(Math.random() * (canvasHeightEnemy - 72));
}
}
function EnemyWidthPicker(type)
{
if (type == "Hover")
{
return 90;
}
}
function EnemyHeightPicker(type)
{
if (type == "Hover")
{
return 72;
}
}
for(var i = 0; i < enemies.length; i++)
{
enemies[1].draw();
}
should probably be
for(var i = 0; i < enemies.length; i++)
{
enemies[i].draw();
}
...or you'll draw the same enemy over and over.
In your drawAllEnemies function, shouldn't
enemies[1].draw();
be
enemies[i].draw();
?
When you loop the enemies array you should use the index i that you setup so that it doesn't continually draw the same element:
for(var i = 0; i < enemies.length; i++)
{
enemies[i].draw();
}

Categories

Resources