Javascript is a single thread language. It enqueues the next statement into its stack to perform the operations. For example:
function sayhello(name){
var greeting="Hello "
checkthis()
console.log(greeting+name)
}
In the above function, we have 3 statements. Suppose checkthis function has ajax or asynchronous process, so it will not wait for the completion of the checkthis( until its using promise), instead, it will enqueue 3rd statement and it will run before the completion of 2nd statement.
While working on the projects, you might find a situation where you will think the process should not continue until some event is not fired or triggered or flagged.
Let’s explore it with an example:
<button id="filebrowserbtn" @click="openFilebrowser"></button>
<button id="getfilebtn" @click="getFile"></button>
<script>
var selectedfile = false
//Function open a filebrowser which would be having a getfilebtn
//This function has such process, where it need to check selectedfile to process further code
function openfilebrowser(){
//Before code here
var delay=200
let process = function() {
if (selectedfile == false) {
setTimeout(process, delay);
}else{
//Execute the code here
selectedFile = false
return filename
}
}
setTimeout(process, delay);
}
//This function will change the Flag of selected file
function getFile(){
selectedfile=true
}
</script>
In the above code, we have used the setTimeout function to wait and check for the event to trigger. This event changed the Flag status and due to setTimeout, it looked for the Flag on the specific interval. It will not take much memory as well.
It’s a real-world issue which generally occurs, so tried to come up with some solution. I hope it might help you. Please let me know if you have any issues, suggestions or feedback.
Be First to Comment