Pergunta de entrevista da empresa Infosys

Callback ? why it is used?

Respostas da entrevista

Sigiloso

6 de mar. de 2020

JavaScript is asynchronous in nature. However we want execute another function after current one, we used callback function. Because of callback another function wait until current one completes the functionality.

1

Sigiloso

30 de jul. de 2022

A: JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming. Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors. In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how… Example: -------- const message = function() { console.log("This message is shown after 3 seconds"); } setTimeout(message, 3000); Description: ------------ There is a built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds). So here, the “message” function is being called after 3 seconds have passed. (1 second = 1000 milliseconds)