I'm trying to get five inputs from the user.
I know that calling functions in a loop (like in the below code) will crash, because all of the prompt()'s are getting called at the same time.
for(var i = 0; i < 5; i++) {
prompt();
}
What solutions are there for this? I saw other snippets using a "timeout" with a set amount of time to wait between each function call, but would the code still work when the user can take as much time as they want to enter their prompt?
I know that calling functions in a loop (like in the below code) will crash, because all of the prompt()'s are getting called at the same time.
That't not the case here because prompt is a blocking function, just like alert. I.e. iteration (or rather code execution) only continues after the prompt windows was closed.
You could add all the values to an array like so:
var inputs = [];
for(var i = 0; i < 5; i++) {
inputs.push(prompt());
}
console.log(inputs);
Whether that's the best user experience is a different question...
No need for a timeout, the prompt will wait for user input (ok, cancel) before the rest of the code executes, meaning that the next prompt will come after clicking ok. The timeout is only usefull so that people do not accidentally press twice ok in a row and see the prompt appear.
Related
This may be a quite naive question but I really need some help.
Prior to writing this post, I was programming on JSBin. Turns out without me realizing, I ran a setInterval loop prompting for userInput and it kept on looping, making me unable to click anywhere to change the code to fix the loop. It kept on repeating and repeating. It got to the point where I had to refresh and lose all my hard-written-code (I was not logged in, so my code was not saved)! I want to avoid that next time.
So, my question is how do I stop any such kind of setInterval Loops, so that I am able to access my code and change it and re-run it. Below is a code that demonstrates my issue, if you try running it on JSBin.com (obviously, it is not the code I wrote before). As you can see, I can not click on my code to change it (or save it) in any way, which means I lose all my code!
This may seem like a useless question, but I really want to know ways to fix it and perhaps fixing it from the developer tools will help me be familiar with the overwhelming set of tools it has :P. So please help me if you know a solution.
Thank you for taking your time to help me! I appreciate it.
setInterval(demo,1);
function demo()
{
var name = prompt("Enter your name: ");
}
Another option is to search the developer tools "Elements" panel for the iframe (this should be doable even if the main document is unresponsive due to prompt's blocking) - then, just right click the iframe element and remove it, no need to type any Javascript. (or, if you want you can select the iframe with querySelector and remove it, eg document.querySelector('iframe').remove())
That's kind of a hack and should only be used in cases like the one exposed in OP but,
About all implementations use integers as timerid that just get incremented at every call.
So what you can do, is to clear all timeouts that were created on the page.
To do so you need to first get to which timerid we are, then call cleatTimeout or clearInterval (they do the same) in a loop until you reach the last call:
function stopAllTimers() {
const timerid = setTimeout(_=>{}); // first grab the current id
let i=0;
while(i < timerid) {
clearTimeout(i); // clear all
i++;
}
};
btn.onclick = stopAllTimers;
// some stoopid orphan intervals
setInterval(()=>console.log('5000'), 5000);
setInterval(()=>console.log('1000'), 1000);
setInterval(()=>console.log('3000'), 3000);
const recursive = () => {
console.log('recursive timeout');
setTimeout(recursive, 5000);
};
recursive();
<button id="btn">stop all timeouts</button>
Assuming the dev tools are closed, hit esc and f12 nearly simultaneously. This should open the dev tools. If it doesn't keep trying until it does.
Once they are open, hit esc and f8. Again, retry til it halts javascript execution at some arbitrary point in the code.
In the "sources" tab locate the generated script for what you wrote (offhand I don't know how it would look like from within JSBin) and literally delete the var name = prompt("Enter your name: "); line. Hitting f8 again will continue execution as if the "new" code is running. This should free you up to copy/paste your code from the site itself before you refresh the page
I'm pretty new to javascript, so apologies for the beginner question. Basically, I am having some problems with the window.open() method.
My code essentially takes a user string, adds a couple different variations to it, and those searches those different variations, and then is supposed to open a new window with each result. However, it seems that after my first window.open statement, the code stops executing. This is what I am working with:
var searchStrings = new Array(url1, url2, url3);
var arrayLength = searchStrings.length;
for (var i = 0; i<arrayLength; i++) {
window.open(searchStrings[i]);
}
I have tested the loop with code other than window.open to make sure it iterates through the array correctly, and I have set i to values higher than 0 to test opening the second or third item in the array.
It seems like window.open is only meant to be used once, or am I doing something else incorrectly?
Check this out: https://javascript.info/popup-windows
This documents correct usage of window.open() functionality.
Modern browsers block that kind of execution, due the risk of mis-using the functionality.
Imagine, you enter the page and 10x windows open, for no reason.
Actually, have a look you code works but chrome blocks the window and on the address bar you are notified. However Firefox blocks it completely, until manually disable the option.
windows.open can takes second parameter(name), if you want open multiple URLs you have to set unique name for each one. in your scenario you cant use this:
for (var i = 0; i < arrayLength; i++) {
window.open(searchStrings[i], '_wnd' + i);
}
I'm new to programming so this question may be really basic but I need some help.
I have a code for generating a message a certain no. of times from input given by the user.
(ex.)
var count=document.getElementById("count").value;
for(var i=0;i<count;i++)
{
GenerateMessage();
}
function GenerateMessage()
{
\*
...*/
}
But no what matter the value of count is the function is executed only once. Am I doing something wrong?
EDIT: Works fine with breakpoints. But during program execution program generates one message irrespective of count value goven by user
It should be
document.getElementById("count").value
Value is a property, not a function.
try this //jsfiddle.net/W4Km8/286/ its useful for you
I am creating a multiple choice question that requires the user to click an answer (radio button). If the user clicks the check answer button before selecting an answer, he is prompted to select an answer. This works fine. However, if the user then selects a wrong answer and clicks the check answer button, the appropriate response is displayed over the previous prompt. I tried changing the getElementById for the prompt to display "", but it didn't work. Any help would be appreciated.
for (i = 0; i < len; i++) {
if (document.Questions.Q_ans[i].checked == false) {
document.getElementById("reply_b").innerHTML = "Select answer before continuing.";
}
}
if (document.getElementById('answer_b').checked || document.getElementById('answer_c').checked) {
document.getElementById("reply_a").innerHTML = incorrect;
document.getElementById("reply_b").innerHTML = "";
}
This line fails since incorrect should either be defined as a variable or it should be wrapped in quotes:
document.getElementById("reply_a").innerHTML = "incorrect"; // <-- Should be in quotes
So your script never executes the line after.
Use Jquery, replace all the "document.getElementById('yourId')" for "$('#yourid')"
and you must have initialized a var len for your loop.
js:
for (var i = 0; i < len; i++) {
if (document.Questions.Q_ans[i].checked == false) {
$("#reply_b").innerHTML = "Select answer before continuing.";
}
}
if ($('#answer_b').checked || $('#answer_c').checked) {
$("#reply_a").innerHTML = incorrect;
$("#reply_b").innerHTML = "";
}
As #brian buck said, your script doesn't get executed after the incorrect statement which should be a defined variable or wrapped in quotes (to be executed as a string). Your script silently fails and basically does nothing (at least, nothing you can see).
A few things here I would also recommend:
Make sure to use var i in your loop to avoid scope error
Your first loop check seems a bit odd to me: for every (assumed) possible answer not checked, you display the same error. It is not critical, but your script does something each time instead of once. You could have, let's say, a boolean that you toggle when you discover that an answer has been checked somewhere, and assign your error statement at the end depending on the value of this boolean. However, my "naked" JS is a bit rusty for that situation, and I am totally sure that there are better solutions to it!
As it appears you haven't been notified of the script failure, I don't think you use any debugger. If you are doing JS in a web browser, you could use the embedded consoles. Otherwise, there are plenty of tools taht could help you a lot. I remember losing my hair when starting to play with JS, because it got silent everytime it wasn't happy...
For loop with ajax call after, slow for loop?
for (var x = this.from; x < this.emax; x++) { this.list.append('<li></li>'); }
jQuery.ajax({
.....
Some how, it will start the ajax request at the same time as the for loop. So Chrome
chokes a second. I dont want that, can it be fixed?
From what i've seen, browsers typically don't update the page til the script is done processing the current event. That means that the Ajax request will be started before the new LIs are actually rendered, and both will appear to happen at about the same time.
One workaround for that would be to put the .ajax call inside a setTimeout with a minimal timeout value. A 0 ms timeout might do it; if not, then 1 will. The point is to get the call queued, so the DOM changes are applied before it occurs.
(With that said, though, why are you appending a bunch of empty LIs in the first place? If they're placeholders for whatever the Ajax request is getting, you might consider letting its success callback add them. Just a thought.)
May be this is work ı am not sure :
for (var x = this.from; x < this.emax; x++) { this.list.append('<li>
</li>').slow(200,function() {
jQuery.ajax({
.........
}); }