Что такое addEventListener в javascript | #7 | JavaScript для начинающих
Вопросы для собеседования в IT (React, JS, CSS, Typescript, общие вопросы) Часть 3
💬 Простыми словами:
Асинхронный код — это код, который не блокирует выполнение программы, а "ждёт" завершения операции (например, загрузки данных). 🛠 Основные способы: 🧪 Примеры: // callback
setTimeout(() => console.log('через секунду'), 1000);
// promise
fetch('/api').then(res => res.json()).then(data => console.log(data));
// async/await
async function load() {
const res = await fetch('/api');
const data = await res.json();
console.log(data);
} 💡 Полезно знать:
Промисы и async/await помогают избежать "callback hell" — вложенных уровней коллбеков...
Debouncing const input = document.querySelector(".custom-input"); // ❌ Before implementation const searchResults = (event) => { // Your core logic will be here! console.log(event.target.value); }; if (input) { // Triggers for each keystrokes input.addEventListener("input", searchResults); } // ✅ After implementation const debounce = (cb, delay) => { let debounceTime; return (...args) => { clearTimeout(debounceTime); debounceTime = setTimeout(() => { cb(...args); }, delay); }; }; if (input) { // being debounced with a delay of 500 milliseconds input.addEventListener("input", debounce(searchResults, 500)); } Throttling const height = document.querySelector("#height"); const width = document.querySelector("#width"); // ❌ Before implementation // invokes for each change const handleResize = () => { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; // Your business logic over here }; (() => { handleResize(); })(); window.addEventListener("resize", handleResize); // ✅ After implementation // invoke only once every 500 milliseconds (given delay) const throttle = (cb, delay) => { let throttling = false; return (...args) => { if (!throttling) { throttling = true; cb(...args); setTimeout(() => { throttling = false; }, delay); } }; }; window.addEventListener("resize", throttle(handleResize, 500));