If someone born into JavaScript, they know what is meant by JavaScript is single threaded. Developers coming from other languages also knows that JavaScript is single threaded. But some APIs in JavaScript force them to think that JavaScript is multi threaded. Below is such a situation
setTimeout(() => { console.log('Timeout hit and time is ' + new Date()); }, 1000); console.log('setTimeout at ' + new Date());
There could be N number of reasons for someone wants to execute his code after specified time. It might be initialization delay, rendering time, session timeout handling etc... But is this going to solve the problem by executing the code exactly after 1 second (1000ms)?
If we consider any application there will be more code than these 2 lines. Consider someone else written below code which got executed after we register the handler via setTimeout()
setTimeout(() => { console.log('Timeout hit and time is ' + new Date()); }, 1000); console.log('setTimeout at ' + new Date()); problemMaker() function problemMaker() { //Any sync AJAX call or some code which execute for long time. var url = 'https://httpbin.org/delay/5'; var request = new XMLHttpRequest(); request.open('GET', url, false); request.send(); document.writeln(request.responseText.length);
}
Does this ensure that the function gets executed after 1 second? Native JavaScript developers can immediately identify the issue. Other may think it might work. Lets see a test run result in console.
setTimeout at Tue Oct 24 2017 19:46:14 GMT-0400 (Eastern Daylight Time)
Timeout hit and time is Tue Oct 24 2017 19:46:29 GMT-0400 (Eastern Daylight Time)
Yes JavaScript is single threaded whatever we do with setTimeout or setInterval functions. Better do no trust them on when they are going to execute. If we write like this it may work on development machine and may fail in higher environments such as business testing, staging or production. Highly inconsistent issue. Lets avoid saying "It works in my machine".
Sample code located at https://plnkr.co/edit/uexi2U
No comments:
Post a Comment