hi i’m having a problem with this code. my problem is that the first console.log(smile_per_sec) gives me the the value i need, but the second one gives me the value that i’ve given it when i declared the variable.
$.getJSON(
twitter_api_url + '?callback=?&rpp=100&q=text::)',
function(data) {
$.each(data.results, function(i, tweet) {
//console.log(tweet);
// Before we continue we check that we got data
if(tweet.text !== undefined) {
//here we save the time of our happy tweet
var date_tweet = new Date(tweet.created_at);
per_sec[i] = date_tweet/1000;
//console.log(per_sec[i]);
}
});
//here we calculate how manny happy tweets the world tweets per second
smile_per_sec = 100/(per_sec[0]-per_sec[98])
$('#tweet_container').append(smile_per_sec + "<br>");
console.log(smile_per_sec);
return smile_per_sec;
}
);
console.log(smile_per_sec);
it’s probably an easy fix but stil your help would be verry much appreciated.
I’m assuming you want to compare it in the two places I notate below:
Place two executes immediately, place one waits until the getJSON has occurred. This is called asynchronous programming. You can’t use the value until you get it, and if you want something to “wait for the other thing to finish” you need to adopt flexibile async programming techniques.
Any time people talk about eventing or callbacks in javascript, that’s what they’re talking about. In this case, your callback starts
function(data)on the third line.I feel the need to elaborate, let me do so:
These two operate in effectively “the same time”. The thing that happens in getJSON gets stuck on the backburner till it’s done, letting your page keep doing stuff. So that console.log just goes ahead and pops on out, but the back burner hasn’t come back to the front, the water isn’t boiling yet. So until the water boils (could be 10ms, could be 3 minutes) you can’t do anything with the water, or the noodles in the water, or whatever.
I realize this is tricky to grasp at first, but once you get this, you’ll get this whole ajax thing.
To answer the question of “how do I make it do everything when it finishes” the answer is to restructure your code like this: