• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Callbacks in JavaScript

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
What is a Callback?


A callback is a function passed into another function, to be called later when something happens or a task is finished.

Analogy:

Imagine you order food and give the restaurant your phone number so they can call you when your food is ready. Your phone number is the callback.

Why Are Callbacks Important?


JavaScript is single-threaded and often needs to wait for things (like loading data or waiting for a user action).

Instead of stopping everything, it uses callbacks to say, “Do this later, when the waiting is done.”

How Do Callbacks Work?

1. Writing a Function That Accepts a Callback


function doSomethingLater(callback) {
console.log("Doing something...");
callback();
}
2. Defining the Callback Function


function sayHello() {
console.log("Hello, I'm the callback!");
}
3. Passing the Callback


doSomethingLater(sayHello);

Output:


Doing something...
Hello, I'm the callback!
4. Using Inline (Anonymous) Callbacks


doSomethingLater(function() {
console.log("This is an inline callback!");
});
Real-Life Applications


setTimeout and setInterval


setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);

Event Listeners


button.addEventListener('click', function() {
console.log("Button clicked!");
});

Fetching Data (with Promises, but still uses callbacks)


fetch('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
Common Misconceptions


  • Callbacks are not always asynchronous.

    Some callbacks are called right away.


  • Callbacks are just functions.

    There’s nothing special about them except how they’re used.
Callback Cheat Sheet


Definition:

A callback is a function you pass to another function to be called later.

Basic Example:


function callback() { ... }
someFunction(callback);

Anonymous Example:


someFunction(function() { ... });

Typical Uses:


  • setTimeout, setInterval


  • Event handling (like clicks)


  • Fetching data from APIs

Key Point:

Callbacks help JavaScript handle tasks that take time, so your code can keep running without waiting.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу