Why is function not executed when webpage is opened in browser? - javascript

I am trying to create a function that loops infinitely until user inputs that they would like to exit. Every time I open up the webpage in the browser, however, no prompt box appears and the infiniteLoop() function does not execute. Why is the infiniteLoop() function not being called?
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
var tryAgain= prompt("Exit loop?");
if (tryAgain != "Yes") {
infiniteLoop();
}
}
}

You need to call the function in the window onload event.
window.onload = function(){
infiniteLoop();
}
or, if you're using jquery
$(function() {
infiniteLoop();
});

The prompt box doesn't appear because you didn't call the function when your web page loads.
Add infiniteLoop() after you declare your function.
e.g.
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
while (i < 5) {
var tryAgain= prompt("Are you sure?");
if (tryAgain == "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
}
// Initial call
infiniteLoop();

IT WORKS, write 5 times "Yes"(case sensitive) it finishes, otherwise it works infinitely, and do not forget to call infiniteLoop()

Cleaned up and working
(function infiniteLoop() {
var begin = prompt("Shall we begin?");
if (begin === "Yes") {
var i= 0;
while (i < 5) {
var tryAgain = prompt("Are you sure?");
if (tryAgain === "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
})()

Related

How to break a for-loop with a nested setTimeout() function in javascript?

The Situation
I have a function which is called on button click and which should draw an animated chart, updating the chart every 2 seconds. When the user clicks that button again, while the animation is still running, the animation should stop.
My current solution
Right now I have the following script which stops the animation visually, but the underlying for-loop continues until the end in the background:
var animRun = false;
$("#animateButton").on("click", function() {
if (animRun === false) {
redraw(data.slice(0,30))
//some CSS...
} else {
//Some CSS...
animRun = false;
}
});
function redraw(data) {
animRun = true;
for (var i=0; i<data.length;i++){
(function(i){
setTimeout(function(){
if(animRun === true) {
//draw the chart
return draw(data[i])
}
},2000*(i))
if (i === data.length -1) {
//reset animRun
if(animRun === true) {
//Some CSS things
//...
animRun = false;
}
}
})(i);
}
}
Question
What would be the correct way of stopping the for-loop when the user clicks the button again while the animation is still executing?
Did you try clearTimeout. Store your draw timeout to an array, and stop it when you done
var animRun = false;
var drawArr = [];
$("#animateButton").on("click", function() {
if (animRun === false) {
redraw(data.slice(0,30))
//some CSS...
} else {
//Some CSS...
animRun = false;
drawArr.forEach(d=>clearTimeout(d));
}
});
function redraw(data) {
animRun = true;
for (var i=0; i<data.length;i++){
(function(i){
drawArr[i] = setTimeout(function(){
if(animRun === true) {
//draw the chart
return draw(data[i])
}
},2000*(i))
if (i === data.length -1) {
//reset animRun
if(animRun === true) {
//Some CSS things
//...
animRun = false;
}
}
})(i);
}
}

Javascript break/continue statement

I can't get this working:
var x = 1;
while (x == 1) {
}
function changeX(val) {
if (val == 1) {
x = 1;
} else if (val == 0) {
x = 0;
break;
}
}
and no matter what I do, I can't get this working. What I want to do is: I want the loop to stop working when I choose "0" or type it or anything. I have to use break/continue .
No matter what I do, I get wrong use of break or my browser crashes.
PS. In HTML part I put
<input type="text" value="1" onchange="changeX(this.value)">
Making your code work:
While will block the browsers thread. Therefore, you cannot click.
Do:
var x=false;
function react(){
if(x){return;}
//your code
console.log("sth");//e.g.
setTimeout(react,0);
}
react();
Now you can do your UI stuff
function changeX(val) {
if (val == 0) {
x = true;
}
}
What you really want:
var timer=false;
function input(val){
if(timer){
clearInterval(timer);
timer=false;
}
if(val){
timer=setInterval(function(){
val++;
alert(val);
if(val==10){
clearInterval(timer);
timer=false;
}
}, 1000);
}
<input oninput="input(this.value)">
<h3>Break Statement</h3>
<script>
let num=0;
while(num<5){
num++;
if((num==3)){
break;
}else{
document.write("num is: "+num+"<BR/>")
}
}
document.write("When if condition is true: while Loop Terminated");
</script>
<h3>Continue Statement</h3>
<script>
let val=0;
while(val<5){
val++;
if(val==3){
// skip the current loop iteration and jump to the next iteration
continue;
}
document.write("val = "+val+"<BR/>");
}
</script>

How can i clearInterval(myFunc) after myFunc has executed 5 times?

The purpose of the code below is to alert online shoppers that they must select a color (via a select/option menu) before putting an item into their basket. If they don't select a color (ie, make a selection) some blinking text displays alerting them.
I'm trying to have the text blink 3 times then stop. I tried using some counter vars but didn't work. How can I re-write this so the blink executes 3 times only?
function blink() {
if ($('.pleaseSelect').css('visibility') == 'hidden') {
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
}
}
function showNotice() {
timerId = setInterval(blink, 200);
}
$('#addToCart').click(function() {
if ($("select > option:first").is(":selected")) {
showNotice();
} else {
clearInterval(showNotice);
$('.pleaseSelect').css('visibility', 'hidden');
}
})
Well you can have counter declared and incremented each time blink is called. then check if you have called blink three times, clear the interval. Also your showNotice function is not defined properly.
var counter = 0,
timerId;
function blink() {
if ($('.pleaseSelect').css('visibility') == 'hidden') {
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
if (counter > 4) {
showNotice(false);
}
}
counter++;
}
function showNotice(show) {
if (show) {
timerId = setInterval(blink, 200);
} else {
clearInterval(timerId);
counter = 0;
}
}
$('#addToCart').click(function () {
if ($("select > option:first").is(":selected")) {
showNotice(true);
} else {
showNotice(false);
$('.pleaseSelect').css('visibility', 'hidden');
}
})
Here is working fiddle
function blink(){
var blinkCount = 0;
return function () {
if($('.pleaseSelect').css('visibility')== 'hidden'){
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
}
blinkCount = blinkCount + 1;
if (blinkCount === 3) {
clearInterval(timerId);
}
}
}
the only thing is that timeId is global - bad practice... however you would have to refactor more of your code in order to correct that issue.
another option is to just fadIn and fadeOut rather than what you're doing.
It would look something like:
if(element.val() == ''){
element.fadeOut("fast");
element.fadeIn("fast");
element.fadeOut("fast");
element.fadeIn("fast");
element.fadeOut("fast");
element.fadeIn("fast");
}
How about this example? Use an anonymous function to call your blink method and keep decrementing a counter.
id = setInterval(function () {
counter--;
if (!counter) {
clearInterval(id);
}
blink();
}, 200);
See the JSFiddle for the complete context.
You can accomplish the desired behavior using variables within a private scope:
$('#addToCart').click(function(e) {
blink(e);
});
function blink(e) {
var blink_count = 0;
var timer = setInterval(function(e) {
blink_count++;
$('.pleaseSelect').toggle();
if (blink_count >= 6) {
clearInterval(timer);
blink_count = 0;
}
}, 200);
}

Input button never appears when javascript detects form completed

I'm making a register page using HTML, CSS and JS and Java servlet etc. I have a monitorer() function which checks if the user has finished inputting everything before making the register button visible. But now everything works, but somewhere am getting screwed over and the button never comes back..
my button in reg.html :
<input type="submit" value="Register" class="btnSub" id="btnReg" style="visibility:hidden;"/>
javascript function monitorer()
function monitorer() {
var btnReg = document.getElementById("btnReg");
btnReg.style.visibility = "hidden";
var flag = true;
if (document.getElementById("fname").value.length >= 3) {
if (document.getElementById("lname").value.length >= 3) {
if (valiDate(document.getElementById("dob"))) {
if (document.getElementById("USN").value.length == 10) {
if (document.getElementById("passw").value.length > 5) {
var ticks = document.getElementsByClassName("checker"), i = 0;
for (i = 0; i < ticks.length; i++) {
if (ticks.item(i).innerHTML == "✔") {
alert("i val = " + i);
continue;
} else {
flag = false;
break;
}
}
}
} else {
flag = false;
document.getElementById("USN").focus();
}
} else {
flag = false;
document.getElementById("dob").focus();
}
} else {
flag = false;
document.getElementById("lname").focus();
}
} else {
flag = false;
document.getElementById("fname").focus();
}
if (flag == true) {
btnReg.style.visibility = "visible";
} else if(flag == false) {
btnReg.style.visibility = "hidden";
}}
And to help you get as good a picture as you can, a screenshot
See - all the ticks are there, the first name, last name etc are having value.length >=3 but still the register button doesn't show..
Also, I have put the monitorer() method in every input's "onBlur", "onChange" events.
Here is a link to my html file >>> reg.html
and please let me know if i can improve anything?

ajax hidding div problem in IE

I have a javascript page which checks an email and username, this works fine in every browser but Internet Explorer. The div box where errors are shown should be hidden unless an error is given e.g. username taken or invalid email.
If the email gets an error this is shown in the div tag, but doesnt work for username (in all browsers)
below is my code:
<script type="text/javascript">
var usernameok;
var emailok;
function checksubmit()
{
if (usernameok && emailok) {
document.getElementById("button").disabled = false;
} else {
document.getElementById("button").disabled = true;
}
}
function username(username)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Username Ok") >= 0) {
usernameok = true;
} else {
usernameok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
user_url = "check_username.php?username=" + username.value;
httpxml.open("GET", user_url, true);
httpxml.send(null);
}
function email(email)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
emailok = true;
} else {
emailok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
email_url = "check_email.php?email=" + email.value;
httpxml.open("GET", email_url, true);
httpxml.send(null);
}
</script>
I see your function stateck() is the return function from the HTTP request. However, you are defining it within another function. Not as an anonymous function, but just as a function within another function.
I see what you're doing now...ok, try this instead:
httpxml.onreadystatechange = function()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
document.getElementById("email").style.backgroundColor = "green";
document.getElementById("email").style.color = "white";
document.getElementById("email_div").style.display = 'none';
emailok = true;
} else {
document.getElementById("email").style.backgroundColor = "red";
document.getElementById("email_div").innerHTML=httpxml.responseText;
emailok = false;
}
checkCanSubmit();
}
};
Do you need to set your initial state to display: none? I think IE may initialize the divs with a non-0 height whereas the divs may be technically visible in other browsers but too short to see.
Edit:
Okay I think I misunderstood your question. Your problem is not with hiding the divs but with displaying errors for the username.
Nothing obvious jumps out at me. Try stepping through the code using VS or VWDE:
http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/

Categories