Recursion with arguments method - javascript

The script must have to print 'Hello', then 'Good bye', because of the entries on function call. But only prints once. Why?
What's wrong here bellow.
PD: Now it doesn't work. It does if i comment the recursion call line
<html>
<head>
</head>
<body>
<script type="text/javascript">
function writing(i,first,second) {
len=arguments.length;
if (i<=len) {
current=arguments[i];
c=0;
inter=setInterval(function() {
if (c>=current.length) {
clearInterval(inter);
} else {
field=document.getElementById('div1');
field.innerHTML+=current[c];
c+=1;
}
},200);
}
i<len?writing(i+1,first,second):writing(i=0,first,second);
}
writing(1,'Hello','Good bye');
</script>
<div id="div1"></div>
</body>

There are so many problems with the code , first was it was infinite loop (never ending) , second was variable declaration , and others...
Here I have attached the snippet , please run and check, if its that you are looking for.
I have to add setTimeout for fullfill your requirement.
var interval_counter = 0;
function writing(i, first, second) {
var len = arguments.length;
if (i != 0 && i <= len) {
var current = arguments[i];
var c = 0;
setTimeout(function() {
var inter = setInterval(function() {
if (c >= current.length) {
clearInterval(inter);
} else {
field = document.getElementById('div1');
field.innerHTML += current[c];
c += 1;
}
}, 200);
}, 200 * interval_counter);
interval_counter = interval_counter + current.length;
i < (len - 1) ? writing(i + 1, first, second) : writing(i = 0, first, second);
} else {
return false;
}
}
writing(1, 'Hello', 'Good bye');
<div id="div1"></div>

Related

Make a page redirect when a number is 15 using if statements

I want to make a piece of code redirect the user to a certain website after 15 is reached by a number. I would use the code below and it would not redirect even if the number is met.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="text">please wait <span id="thing" style="font-size: 70px;">0</span> seconds<span id="wait"></span></h1>
<script>
var request = document.getElementById("thing");
var num = 0;
var goup = setInterval(function goUp() {
num++;
request.innerHTML = num;
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)
if (num.innerHTML === 15) {
location.href('https://google.com/');
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="text">please wait <span id="thing" style="font-size: 70px;">15</span> seconds<span id="wait"></span></h1>
<script>
var request = document.getElementById("thing");
var num = 15;
var goup = setInterval(function goUp() {
request.innerHTML = --num;
if (num === 0) {
window.location.href = 'https://google.com/';
}
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)
</script>
</body>
</html>
I simply put the if statement inside the interval so it checks every time the 'timer' is updated. Also, I made the timer go backwards because you are telling the user to wait for 15 seconds, so it should be counting down. In addition, I changed location.href() to window.location.href =, since location.href() isn't a function, it's a string, so you need to change it using an assignment operator.
var request = document.getElementById("thing");
var num = 0;
var goup = setInterval(function goUp() {
request.innerHTML = num++;
if (num === 4) {
clearInterval(goup)
location.href = 'https://google.com/';
}
}, 1000)
var dots = window.setInterval(function dots() {
var waiter = document.getElementById("wait");
if (waiter.innerHTML.length > 5) {
waiter.innerHTML = ""
} else {
waiter.innerHTML += ".";
}
}, 100)

How to change two variables to values that are opposite to another

I have a question about changing variables.
I'm making a scoreboard for table tennis. I'm trying to show the players who has to serve. Everytime the x-key gets pressed (/when a point is scored), I check if the right to serve has to change. For this example I removed that bit.
What I'm trying to do:
Everytime an input is detected (keyboard event), the opacity of the first variable is changed to be the opposite from what is was, as well as the second variable.
Perhaps, you could think of it like a railroad crossing.
What is happening:
Only the opacity of the first variable is 1. This is due to the code running from top to bottom. It sees that the currentActionPlayer1 variable is 0, so it makes it 1. But when it reaches the if statement 'currentActionPlayer2 == 0', that is true. So the currentActionPlayer1 variable becomes 0, and cAP2 becomes 1 again.
I don't really know how to explain it any better.
var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;
window.addEventListener("keyup", checkKeyUp);
function checkKeyUp(keyUp) {
if (keyUp.keyCode == "88") { //X
changeActionPlayer();
}
}
function changeActionPlayer() {
if (currentActionPlayer1 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer2 = 1;
changeActionIcon();
}
if (currentActionPlayer2 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer1 = 1;
changeActionIcon();
}
}
function changeActionIcon() {
if (currentActionPlayer1 == 1) {
document.getElementById('actionP1').style.opacity = "1";
document.getElementById('actionP2').style.opacity = "0.2";
}
if (currentActionPlayer2 == 1) {
document.getElementById('actionP1').style.opacity = "0.2";
document.getElementById('actionP2').style.opacity = "1";
}
}
<html>
<head>
</head>
<body>
<p id='actionP1' style='opacity: 0.2'>action</p>
<p id='actionP2' style='opacity: 0.2'>action</p>
</body>
</html>
If I right understand, you need something like this one?
var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;
window.addEventListener("keyup", checkKeyUp);
function checkKeyUp(keyUp) {
if (keyUp.code == "KeyX") { //X
changeActionPlayer();
}
}
function changeActionPlayer() {
if (currentActionPlayer1 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer2 = 1;
changeActionIcon();
} else if (currentActionPlayer2 == 1) {
currentActionPlayer2 = 0;
currentActionPlayer1 = 1;
changeActionIcon();
}
}
function changeActionIcon() {
if (currentActionPlayer1 == 1) {
document.getElementById('actionP1').style.opacity = "1";
document.getElementById('actionP2').style.opacity = "0.2";
}
if (currentActionPlayer2 == 1) {
document.getElementById('actionP1').style.opacity = "0.2";
document.getElementById('actionP2').style.opacity = "1";
}
}
<html>
<head>
</head>
<body>
<p id='actionP1' style='opacity: 0.2'>action</p>
<p id='actionP2' style='opacity: 0.2'>action</p>
</body>
</html>

java script Foreach loop

Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.
You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}
this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();
function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview
If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>
You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>
**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}

scope in angular and applied css class only on first div

I'm calling js function every 2 seconds where on certain condition I want to update div on the view.
<div id="ball_{{ballIndex}}">{{ball}}</div>
on ng controller
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter ++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}
using this code only first div in iteration is applied with class magictime puffIn. When I hardcode div id's on the view side like <div id="ball_1">1</div> <div id="ball_2">2</div> .. applied css class work on each div. What I'm doing wrong?
Update:
Tried with
<div ng-attr-id="{{ 'ball_' + ballIndex }}"> </div>
but problem is still present.
At first you must define
var myCounter =0;
I don't understand ball
you must defined it like this :
$scope.ball=0;
I Change view like this
<div id="ball_{{ballIndex}}">{{ballIndex}}</div>
and your javascript changed like this:
var poolCounter = 0;
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}

Images don't get displayed before a pop-up box

I just started learning Javascript by doing a simple card game and I'm stucked at a problem. I want to show four cards as an image before a user can select a trump by a popup box. But, everytime I run the code the cards images get displayed AFTER the popup box and not before. Please have a look at the relevant code:
function preloadImages() {
var imgs = [];
for (var i = 0; i < max_length_deck; i++) {
imgs[i] = new Image();
imgs[i].src = 'img/' + deck[i] + '.png';
}
}
function generateDeck() {
for (i = 0; i < colour.length; i++) {
for (x = 0; x < number.length; x++) {
deck.push(colour[i] + '' + number[x]);
}
}
}
function shuffleCards() {
cards.length = 0;
for (i = 0; i < max_length_deck; i++) {
var random = Math.floor(Math.random() * deck.length);
cards.push(deck[random]);
deck.splice(random, 1);
}
}
function dealCards() {
generateDeck();
preloadImages();
shuffleCards();
for (var i = 0; i < 4; i++) {
window.document.images[i].src = 'img/' + cards[i] + '.png'; //I defined four image tags at html file
}
selectTrump();
}
function selectTrump() {
var result = false;
while (result != true) {
trump = prompt("Please enter trump:", "");
result = checkTrump(trump);
}
}
I searched and tried several things already (jQuery load handlers; window.setTimeout), but nothing worked and I don't get problem. So, thank you very much for any hint!
BR
Kjaer
In the function Dealcards() you probably have to wait for the images to be loaded first, before dealing the cards. You can use add an eventhandler for this:
<html>
<head>
<script>
function loadImage()
{
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="w3javascript.gif" onload="loadImage()" id="myImage">
</body>
</html>
//Or use:
// example
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
addEvent(
document.getElementById('myImage'),
'load',
function () { alert('image loaded!'); }
);
addEventListener vs onclick

Categories

Resources