I always thought that javascript is a single threaded language (for the most part at least).
As you can see in my code:
<html>
<body>
<a onclick="test();">test</a>
</body>
<script>
var text = "test";
function show()
{
console.log("show(): "+ text);
}
function test()
{
console.log("before: "+text);
change();
console.log("after: "+text);
show();
}
function change()
{
text = stateChange(-1);
}
function stateChange(newState) {
var output = "empty";
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
output = "newText";
console.log("AFTER 5 Sec: "+output);
}
}, 5000);
return output;
}
</script>
</html>
My stateChange function returns a variable already prior to completion of the function. It didn't wait 5 seconds before returning the variable to change() function. Therefore, all the functions inside the test() function were being executed (then of course after 5 seconds the alert shows up).
My question is, is there a way to return variable only when the function is fully completed. It seems like it javascript created another thread to execute other functions. Any way to go around this?
(This happens in ajax as well, where I will have a function i thought i will return after the completion of the ajax call, but turns out the function just return itself right away before finishing the ajax call.)
I want my test() function to work in order.