Javascript global variable usage is acting weird in this code [duplicate] - javascript

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Return Value from inside of $.ajax() function
(3 answers)
Closed 8 years ago.
I am running following javascript as a test using jsfiddle.net -
var v1=1;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
alert('Your current position is:');
alert('Latitude : ' + crd.latitude);
alert('Longitude: ' + crd.longitude);
alert('More or less ' + crd.accuracy + ' meters.');
v1=crd.latitude;
alert(v1);
};
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
};
alert(v1);
navigator.geolocation.getCurrentPosition(success, error, options);
alert(v1); //removing this makes the code work
The code works fine until the last alert is put in place. The success function isn't invoked in that case. I am baffled if it's a global variable declaration issue or the way getCurrentPosition is being invoked. All I want is to have the longitude and latitude values in a variable that I can use later. Newbie here. Any pointers?

Which Browser are you using? The above code works fine in chrome.
The second alert could be halting execution of your success function. better use console.log() for debugging.

Related

Script failing to execute more than once [duplicate]

This question already has answers here:
Javascript Function setInterval() works only one time [duplicate]
(2 answers)
JS setInterval executes only once
(2 answers)
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 months ago.
I am trying to make a chatbot for the web game https://skribbl.io but when my javascript script is run, it only runs once.
function send() {
var ic = document.getElementById("inputChat");
ic.value = "ChatBot online";
ic.parentNode.dispatchEvent(new Event('submit', {
bubbles: false,
cancelable: false,
}));
}
setInterval(send(), 1000);
setInterval(send, 1000);
or
setInterval(() => { send() }, 1000);

how to use prompt function in node.js like in chrome [duplicate]

This question already has answers here:
Using node.js's prompt for user input? [duplicate]
(4 answers)
Closed 1 year ago.
when I use chrome, I can use prompt function like
let name = prompt('What's your name?');
but when I use atom editor which use node.js as a compiler(i'm not sure this is called 'compiler'), the prompt function doesn't work.
I already tried to install 'prompt for node.js' at NPM but it still doesn't work.
Please help me....
Try this:
var prompt = require('prompt');
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
});
This is the result:
I'm using Visual Studio Code, however, the result's properly the same. For more information, see this: https://www.npmjs.com/package/prompt

Setting a global variable inside a JS onload() function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I want to store the length of a Json array as a global variable to make my code more modular. I am trying to set the global variable inside the .onload function but it won't allow this. I have tried with a globalTest variable.
var objectLength = 0;
var globalTest = 0;
$(document).ready(function() {
establishConnection();
});
function establishConnection() {
xttp = new XMLHttpRequest();
xttp.open("GET", "http://exampleServerPath", true);
xttp.send("null");
xttp.onload = function() {
var Json = JSON.parse(this.response);
objectLength = Json.length;
globalTest = 2; // this doesn't work
};
globalTest = 4; //this works
}
I am fairly new to JS any help is appreciated!
I think the issue lies with the xttp.onload part. Change that to xttp.onreadystatechange and then check the readystate.
Check out this example.
EDIT:
Your code works as expected, but maybe you think globalTest is not being updated.
If you were to call establishConnection() and then immediately try to access globalTest it will still be 0 because the AJAX request has not completed yet.
If you did
establishConnection();
setTimeout(function() {
alert(globalTest);
}, 2000);
Then you should see the value you expect (assuming your ajax request completes in less than 2 seconds.

JavaScript only works with a breakpoint set in browser debugger [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a basic function in JavaScript that simply takes some pre-set values and puts them onto the screen by the use of a pre-made function. When I breakpoint the first line of what it is I'm doing, the page loads fine, as expected, but as soon as I remove that breakpoint, none of the information is set. and the page is blank.
this.QuizSelection = function () {
// Fill the ID's with the right info
app.SetBackground('head', this.HeroImage);
console.log('1 ' + this.HeroImage);
app.LoadInnerHTML('breadcrumbs', 'Home / ' + this.Title);
app.LoadInnerHTML('quizSelectionTitle',this.Title);
console.log('2 ' + this.Title);
app.LoadInnerHTML('quizSelectionIntro',this.Introduction);
console.log('3 ' + this.Introduction);
// Show the Quiz Selection and Heading
app.ShowSection('head');
app.ShowSection('quizSelection');
console.log('Quiz Selection');
}.bind(this);
The functions inside that (SetBackground and LoadInnerHTML) are just small one line functions that change the inner html and the set a background image.
// Change Inner HTML
this.LoadInnerHTML = function (id, html) {
var d = document.getElementById(id);
d.innerHTML = html;
}
// Set Background Image
this.SetBackground = function (id, image) {
document.getElementById(id).style.backgroundImage = 'url(image)';
}
I can't understand why it wouldn't work when the breakpoint isn't on. Clearly it does work, because everything is fine with the breakpoint on, but then when it's off the result I get output to the console is:
1
2
3 undefined
Quiz Selection
You have a race condition.
The act of hitting a breakpoint makes your code wait for the async JSON load to complete. Without the breakpoint, the code trying to read the JSON is executing before the JSON has actually loaded.
See How do I return the response from an asynchronous call? for how to fix this issue.
You have console.log statements in your code. When the debugger is not on, console object does not exist (this is true for IE not for Chrome to the best of my knowledge), thus your javascript code execution fails.

Why Does Next Line Execute Before Function Returns a Value?

I have:
var newID = saveNewGame(newName, newShortName, "1");
alert (newID + " Here");
function saveNewGame(newName, newShortName, myNumber) {
myRequest.open("POST", "savegame.php", false);
if (myRequest.status === 200) {
var myNewID = myRequest.responseText;
alert(myNewID + " There");
return myNewID;
}
When ran, I get a popup message: 'undefined Here' followed by a popup message: '5 There'. - More complex code added. The function performs an XMLHttpRequest (myRequest) - but set to Async = false.
I'd think that '5 There' should popup first and 'undefined Here' should say '5 Here' and popup second. Why does this do what it does?
NOTE: I snipped out the XML setup stuff
When I run your code as you show it (with a definition for newName and newShortName in your answer in a jsFiddle here http://jsfiddle.net/jfriend00/a5da81kp/, it does not do what you said it does. In fact, it shows the two alerts with legitimate strings just like one would expect.
It shows:
5 There
5 Here
So, it seems likely that your real code is not as simple as the code you have in your question. I'd guess that you perhaps have some asynchronous code somewhere that does indeed change the order of execution. But the hypothesis in your question is simply not correct. That code works as one would expect.

Categories

Resources