I have seen a lot of function examples for async javascript containing setTimeout, AJAX calls, etc.
Obviously these all have a certain delay meaning the flow of the script is impacted. But I was wondering, what if I have something like this:
function init() {
this.initSlider();
this.testLog();
}
function initSlider() {
// find multiple items and build up a slider instance
// for each of these elements.
}
function testLog() {
console.log('test);
}
If initSlider possible takes a long time will it simply run my testLog function first?
I am currently a bit unsure about this. I know there might be plenty of examples on the flow of javascript but I can't find ones where a simple function would just take a longer time to run.
-
4This doesn't look async, it looks sync to me.N.J.Dawson– N.J.Dawson2016年08月15日 08:13:35 +00:00Commented Aug 15, 2016 at 8:13
-
2This book explains in great detail how async works and should be handled: github.com/getify/You-Dont-Know-JS/tree/master/…. But, your snippet does not expose anything async. We'd need more details.Thor Jacobsen– Thor Jacobsen2016年08月15日 08:15:06 +00:00Commented Aug 15, 2016 at 8:15
-
what hinders you make a test? :) generally spoken, a function in javascript doesnt take much time anyways, so the second function call will not "wait", but of course can only be run as soon as the first function has "finished", regardless of ajax calls.Alex– Alex2016年08月15日 08:15:32 +00:00Commented Aug 15, 2016 at 8:15
-
1@user2521387 you mean I've been wrong to use AJAX for JSON / SignalR / WebApi / REST services all this time and it's only for Javascript to PHP???fdomn-m– fdomn-m2016年08月15日 08:18:42 +00:00Commented Aug 15, 2016 at 8:18
-
1@Stephan-v it doesn't "skip over" any functions. setTimeout says 'run this code later' and ajax calls say 'make this call to the server and run the 'complete' (etc) code when it completes.fdomn-m– fdomn-m2016年08月15日 08:19:47 +00:00Commented Aug 15, 2016 at 8:19
2 Answers 2
It is totally depend on what is there inside initSlider(). Although initslider() is heavy function and do not contain any asynchronus statement then testLog() will not execute first.
Javascript stores all statements in callstack and they will be executed one after the other.
If there is asynchronus statement then it removes that statement outof the callstack and there is chance of your testLog() to execute.
so for your question my answer will be DEPENDS ON CODE INSIDE initSlider()
2 Comments
Javascript is a technology that runs single threaded. When you use asynchronous methods like AJAX or setTimeout the javascript engine processes those parts one by one (if one is waiting something than switching to another and then back and etc...). You can see the javascript's power on async tasks with Node.js. I guess this blog is very good to understand the Javascript and async methods: click_me!