From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../javascript/asynchronous/concepts/index.html | 203 ------- files/he/learn/javascript/asynchronous/index.html | 43 -- .../javascript/asynchronous/introducing/index.html | 281 --------- .../javascript/asynchronous/promises/index.html | 589 ------------------- .../asynchronous/timeouts_and_intervals/index.html | 651 --------------------- 5 files changed, 1767 deletions(-) delete mode 100644 files/he/learn/javascript/asynchronous/concepts/index.html delete mode 100644 files/he/learn/javascript/asynchronous/index.html delete mode 100644 files/he/learn/javascript/asynchronous/introducing/index.html delete mode 100644 files/he/learn/javascript/asynchronous/promises/index.html delete mode 100644 files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html (limited to 'files/he/learn/javascript/asynchronous') diff --git a/files/he/learn/javascript/asynchronous/concepts/index.html b/files/he/learn/javascript/asynchronous/concepts/index.html deleted file mode 100644 index 273c184474..0000000000 --- a/files/he/learn/javascript/asynchronous/concepts/index.html +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: עקרונות תכנות א-סינכרוני כלליים -slug: Learn/JavaScript/Asynchronous/Concepts -translation_of: Learn/JavaScript/Asynchronous/Concepts ---- -
{{LearnSidebar}}{{NextMenu("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous")}}
- -

- במאמר זה אנחנו נעבור על מספר עקרונות חשובים בנושא תכנות א-סינכרוני וכיצד זה נראה בדפדפנים וב-JavaScript. חשוב להבין עקרונות אלו לפני שממשיכים למאמרים הבאים במודול זה. -

- - - - - - - - - - - - -
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה: - הבנה של העקרונות הבסיסיים מאחורי תכנות א-סינכרוני וכיצד אלו באים לידי ביטוי בדפדפנים וב-JavaScript.
- -

Asynchronous - א-סינכרוני?

- -

- באופן נורמלי, קוד של תוכנית רץ בצורה עצמאית, כאשר רק דבר אחד קורה בכל רגע נתון. אם פונקציה מסויימת נשנעת על התוצאה של פונקציה אחרת, היא חייבית לחכות לפונקציה האחרת לסיים ולהחזיר את התוצאה ועד שזה לא קורה, כל התוכנית עוצרת מנקודת מבטו של המשתמש.

- -

Mac אלו המשתמשים ב-, לדוגמא, - לפעמים רואים עיגול צבעוני... עיגול זה בעצם אומר למשתמש ״התוכנית הנוכחית שאתה מתמש בה הייתה צריכה לעצור ולחכות שמשהו הסתיים, וזה לוקח זמן..״

- -

multi-colored macos beachball busy spinner

- -

- זו חווית שימוש מעצבנת, ולא ממש שימוש יעיל ביכולות המחשב, במיוחד בעידן שלמחשבים יש מספר ליבות מעבד זמינות. אין שום סיבה שאנחנו נחכה למשהו כשאנחנו יכולים להמשיך במקביל בעבודה שלנו בזמן שהמחשב עובד על אותה פעולה ויעדכן אותנו כשהפעולה הסתיימה. זה מאפשר לנו לבצע פעולות אחרות במקביל, וזה בעיקרון הבסיס של תכנות א-סינכרוני - asynchronous programming. זה תלוי בסביבת הפיתוח שבה אנחנו משתמשים (דפדני אינטרנט במקרה שלנו) להעניק למפתח APIs שיאפשרו לנו להריץ משימות באופן א-סינכרוני - - -

- -

Blocking code

- -

- טכניקות א-סינכרוניות הן שימושיות מאוד, במיוחד בפיתוח web. כאשר יישום web רץ בדפדפן ומריץ שורות קוד מבלי להחזיר את השליטה לדפדפן, הדפדפן יכול להיראות כאילו הוא ״קפא״. זה נקרא blocking. הדפדפן חסום מלהמשיך ולטפל בפעולות מצד המשתמש ולבצע פעולות נוספות עד אשר יישום ה-web מחזיר את השליטה למעבד.

- -

- נסתכל על מספר דוגמאות על מנת להסביר למה אנחנו מתכוונים ב- blocking - -

- -

ב simple-sync.html דוגמא שלנו (או כ דף אינטרנט), - - הוספנו מאזין אירוע מסוג click לכפתור כך שבכל פעם שהכפתור יילחץ, הוא יריץ פעולה שלוקחת המון זמן (מחשבת 10 מיליון תאריכים ואז מחזירה את האחרון לקונסולה) ולאחר מכן מוסיפה פסקה ל-DOM:

- -
const btn = document.querySelector('button');
-btn.addEventListener('click', () => {
-  let myDate;
-  for(let i = 0; i < 10000000; i++) {
-    let date = new Date();
-    myDate = date
-  }
-
-  console.log(myDate);
-
-  let pElem = document.createElement('p');
-  pElem.textContent = 'This is a newly-added paragraph.';
-  document.body.appendChild(pElem);
-});
- -

- כשאתם מריצים את הדוגמא למלעלה, פתחו את הקונסולה ואז לחצו על הכפתור - אתם תשימו לב שהפסקה אינה מופיעה עד אשר חישוב התאיריכים הסתיים והוצגה ההודעה לקונסולה. הקוד רץ בסדר שבה הוא מופיע בקוד המקור והפעולה האחרונה לא תרוץ עד אשר הפעולה הקודמת לא סיימה.

- -
-

לתשומת לב: הדוגמא הקודמת דיי לא מציאותית. אנחנו לעול לא נחשב 10 מיליון תאריכים בתוכנית אמיתית. דוגמא זו נועדה לתת לכם רק את ההבנה של תכנות א-סינכרוני.

-
- -

בדוגמא השנייה שלנו, simple-sync-ui-blocking.html (ראו כדף אינטרנט), - אנחנו מנסים לדמות משהו קצת יותר ריאלי שאתם אולי תיתקלו בו בדף אמיתי. אנחנו חוסמים את האינטראקציה של המשתמש עם העיבוד של ממשק המשתמש. בדוגמא זו יש לנו שני כפתורים:

- - - -
function expensiveOperation() {
-  for(let i = 0; i < 1000000; i++) {
-    ctx.fillStyle = 'rgba(0,0,255, 0.2)';
-    ctx.beginPath();
-    ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degToRad(0), degToRad(360), false);
-    ctx.fill()
-  }
-}
-
-fillBtn.addEventListener('click', expensiveOperation);
-
-alertBtn.addEventListener('click', () =>
-  alert('You clicked me!')
-);
- -

- אם תלחצו עלהכפתור הראשון ואז ישר לאחר מכן על השני אתם תראו שההודעה למשתמש לא מופיע עד אשר העיגולים לא סיימו להיות מעובדים. הפעולה הראשונה חוסמת את ביצוע הפעולה השנייה עד אשר הפעולה הראשונה תסתיים.

- -
-

לתשומת לב: - זהו אמנם נראה לא טוב, אך זוהי רק דוגמא למה שמפתחים נתקלים בה ביישומים אמיתיים.

-
- -

- מדוע זה קורה? התשובה נעוצה בכך ש-JavaScript היא single threaded. בנקודה, אנחנו נרצה להציג בפניכם את הרעיון של threads.

- -

Threads

- -

Thread הוא בעיקרון תהליך יחיד שתוכנית יכולה להשתמש בה על מנת להשלים משימות. כל תהליך כזה יכול לבצע משימה אחת בכל פעם:

- -
Task A --> Task B --> Task C
- -

- כל משימה תרוץ באופן טורי, רציף, אך לא סימולטני. משימה צריכה להסתיים כדי שהבאה בתור תחל בריצה.

- -

- כפי שאמרנו מקודם, הרבה מחשבים הם בעלי מספר רב של ליבות, כך שהם יכולים לבצע מספר דברים בבת אחת. שפות תכנות שתומכות בליבות מרובות יכולות להתשמש בליבות אלו על מנת לבצע מספר פעולות באופן סימולטני ובמקביל:

- -
Thread 1: Task A --> Task B
-Thread 2: Task C --> Task D
- -

JavaScript - single threaded

- -

JavaScript היא single-threaded. - אפילו אם יש מספר ליבות, אנחנו יכולים רק להריץ משימה על thread יחיד, שנקרא main thread. הדוגמא שלנו מלמעלה מורצת כך:

- -
Main thread: Render circles to canvas --> Display alert()
- -

- לאחר זמן מסויים, JavaScript קיבלה מס׳ כלים על מנת להתמודד עם בעיות אלו. - - Web workers - מאפשר לנו לשלוח חלק מהביצוע של JavaScript ל-thread נפרד שנקרא בשם worker, כך שאנחנו יכולים להריץ קודי JavaScript באופן סימולטני מקביל. בדרך כלל אנחנו נשתמש ב-worker להריץ תהליכי - - allow you to send some of the JavaScript processing off to a separate thread, called a worker, so that you can run multiple JavaScript chunks simultaneously. You'd generally use a worker to run expensive processes off the main thread so that user interaction is not blocked.

- -
  Main thread: Task A --> Task C
-Worker thread: Expensive task B
- -

- כעת, לאחר שאנחנו יודעים זאת, נסתכל על simple-sync-worker.html או כדף אינטרנט, ונפתח את הקונסולה. - בקובץ זה כתבנו מחדש את הדוגמא שלנו לחישוב 10 מיליון תאריכים בworker thread נפרד. כעת כשאנחנו לוחצים על הכפתור, הדפדן מסוכל להציג את הפסקה לפני שחישוב התאיריכים הסתיימו. הפעולה הראשונה כבר לא חוסמת את הפעולה השנייה. - -

- -

Asynchronous code קוד א-סינכרוני

- -

Web workers הם מאוד שימושיים, אבל יש להם הגבלות. - אחת מהן היא שהם לא יכולים לגשת ל-{{Glossary("DOM")}} - אנחנו לא יכולים לגרום ל-worker לעשות שום דבר שיכול לעדכן את ממשק המשתמש, את ה-UI. אנחנו לא נוכל לעבד מיליון כדורים כחולים בתוך ה-worker שלנו. הוא בעיקרון יכול רק לעשות מניפולציות מספריות. -

- -

- הבעיה השנייה היא שלמרות שהקוד שרץ בתוך ה-000000 לא חוסם, הוא עדיין בסופו של דבר סינכרוני. זה הופך לבעיה כשאר פונקציה מתבססת על התוצאה של חישובים של תהליכים שקדמו לפונקציה. הסתכלו על התרשים הבא:

- -
Main thread: Task A --> Task B
- -

- במקרה זה, משימה A עושה משהו כמו הבאת תמונה מהשרת, ואז משימה B עושה משהו עם התמונה הזו, כגון החלת פילטר. אם אנחנו נתחיל את משימה A ואז ישר נריץ את משימה B , אנחנו נקבל שגיאה כי התמנוה עדיין לא זמינה, כי משימה A לא הסתיימה עדיין.

- -
  Main thread: Task A --> Task B --> |Task D|
-Worker thread: Task C -----------> |      |
- -

- במקרה הזה לדוגמא, יש לנו את משימה D שמבצעת שימוש בתוצאות של משימה B ומשימה C. אם אנחנו יכולים להבטיח שהתוצאות של שתי משימות אלו יהיהו זמינות בואתו הזמן, אז זה יכול להיות תקין, אבל זה בדרך כלל לא קורה. אם משימה D תנסה לרוץ לפני שהערכים שהיא צריכה לקבל זמינים עבורה, זה יחזיר לנו רוב הסיכויים שגיאה.

- -

- על מנת לתקן בעיות שכאלו, דפדנים מאפשרים לנו להריץ מס׳ פעולות באופן א-סינכרוני. תכונות כמו Promises מאפשרות לנו לקבוע משימה שתרוץ, כמו לדוגמא הבאת תמונה מהשרת, ולחכות עד אשר התוצאה של אותה משימה תוחזר שנריץ פעולה מסויימת אחרת.

- -
Main thread: Task A                   Task B
-    Promise:      |__async operation__|
- -

- מאחר שהפעולה מתרחשת במקום אחר, ה-main thread לא חסום בזמן שהפעולה הא-סינכרונית מתרחשת. - -

- -

- אנחנו נסתכל כיצד אנחנו יכולים לרשום קוד א-סינכרוני במאמר הבא. -

- -

לסיכום

- -

- עיצוב תוכנה מודרני סובב יותר ויותר סביב שימוש בתכנות א-סינכרוני, כדי לאפשר לתוכניות לעשות יותר מדבר אחד בכל פעם. כאשר נשתמש ב-API חדשים ובעלי יכולות מתקדמות, אנחנו נמצא יותר מקרים שבהם הדרך היחידה לבצע משהו מסויים היא רק באופן א-סינכרוני. זה היה דיי קשה בעבר לכתוב קוד א-סינכרוני. אמנם עדיין לוקח זמן להתרגל לכך, אבל זה נעשה הרבה יותר קל. ביתר המאמרים במודול זה אנחנו נסביר מדוע קוד א-סינכרוני הוא רלוונטי וחשוב וכיצד נעצב את הקוד על מנת להימנע מחלק מהבעיות שסקרנו במאמר זה. - - - יותר מדבר אחד בכל פעם. כשאתה משתמש בממשקי API חדשים וחזקים יותר, תמצא מקרים נוספים שבהם הדרך היחידה לעשות דברים היא בצורה אסינכרונית. פעם היה קשה לכתוב קוד אסינכרוני. זה עדיין לוקח להתרגל, אבל זה נעשה הרבה יותר קל. בשאר מודול זה נבדוק יותר מדוע חשוב קוד אסינכרוני וכיצד לתכנן קוד שנמנע מכמה מהבעיות שתוארו לעיל.

- -

במודול זה

- - diff --git a/files/he/learn/javascript/asynchronous/index.html b/files/he/learn/javascript/asynchronous/index.html deleted file mode 100644 index 01ec7babb7..0000000000 --- a/files/he/learn/javascript/asynchronous/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Asynchronous JavaScript -slug: Learn/JavaScript/Asynchronous -translation_of: Learn/JavaScript/Asynchronous ---- -
{{LearnSidebar}}
- -

במודות זה אנחנו נסתכל על {{Glossary("asynchronous")}} {{Glossary("JavaScript")}}, ומדוע זה חשוב, וכיצד אנחנו יכולים להשתמש בזה על מנת לטפל בפעולות חוסמות () כמו הבאת משאבים מהשרת.

- -

Prerequisites

- -

Asynchronous JavaScript הוא יחסית נושא מתקדם ואנו ממליצים לכם לעבור על המודולים צעדים ראשונים ב-JavaScript ועל אבני הבניין של JavaScript לפני שתתחילו ללמוד מודול זה.

- -

אם אינכם בקיאים בקונספט של תכנות א-סינכרוני, אנא התחילו עם המאמר עקרונות תכנות א-סינכרוני במודול זה. אם אתם כן בקיאים, אתם ככל הנראה יכולים להתחיל ב-הצגת Asynchronous JavaScript.

- -
-

הערה: אם אתם עובדים על מחשב\טבלט\מכשיר אחר שאין לכם אפשרות ליצור עליו קבצים אישיים, אתם יכולים לנסות את (רוב) דוגמאות הקוד על תוכנות קוד אינטרנטיות כמו JSBin או Thimble.

-
- -

מדריכים

- -
-
עקרונות תכנות א-סינכרוני כלליים 
-
-

במאמר זה אנחנו נעבור על מספר עקרונות חשובים בנושא תכנות א-סינכרוני וכיצד עקרונות אלו באים לידי ביטוי בדפדפנים וב-JavaScript. אתם אמורים להבין עקרונות אלו בטרם תמשיכו למאמרים נוספים במודול זה.

-
-
הצגת Asynchronous JavaScript
-
במאמר זה נסקור בקצרה את הבעיות הקשורות ל-JavaScript סינכרונית, ונסתכל לראשונה על האופציות השונות ב-JavaScript א-סינכרוני שניתקל בהן, ונראה כיצד טכניקות אלו יכולות לפתור לנו בעיות.
-
Asynchronous JavaScript: שימוש ב-Intervals ו-Timeouts
-
במאמר זה נסתכל על המתודות המסורתיות שקיימות ב-JavaScript להרצת קוד בצורה א-סינכרונית לאחר שזמן מסויים עבר או בקבועי זמן מסויימים ונדון במקרים שהם רלוונטיים לשימוש וכן נדון בסוגיות הטבועות בהם.
-
טיפול בפעולות א-סינכרוניות באמצעות Promises
-
Promises הם בעיקרון תכונה חדשה יחסית של שפת JavaScript המאפשרת לך לדחות פעולות נוספות עד      לאחר השלמת הפעולה הקודמת, או להגיב לכישלונה. זה מאוד שימושי להגדרת רצף של פעולות שיעבדו בצורה מסויימת. מאמר זה מראה לך כיצד promises עובדות, היכן תראה אותן בשימוש ב- WebAPIs,      ואיך לכתוב promises משלך.
-
הפיכת Asynchronous Programming לקל יותר עם async ועם await
-
Promises יכולות להיות קצת מורכבות לביצוע והבנה, ודפדפנים מודרניים הטמיעו את הפונקציות async ואת האופרטור await - הראשון מאפשר לפונקציות סטנדרטיות להתנהג בצורה עקיפה כא-סינכרוניות עם Promises ואילו בשני אנחנו יכולים לעשות שימוש בתוך פונקציות async על מנת לחכות ל-promises לפני שהפונקציה ממשיכה, כך שנוכל לקשור promises בצורה קלה יותר. מאמר זה מסביר את async/await.
-
בחירת האפשרות המתאימה
-
בסיום המודול אנחנו נדון בהבדלים שבין הטכניקות השונות שנגענו בהם, ונדון באיזו טכניקה יהיה מומלץ להשתמש במקרים השונים.
-
- -

ראו גם

- - diff --git a/files/he/learn/javascript/asynchronous/introducing/index.html b/files/he/learn/javascript/asynchronous/introducing/index.html deleted file mode 100644 index 3f5a342e1e..0000000000 --- a/files/he/learn/javascript/asynchronous/introducing/index.html +++ /dev/null @@ -1,281 +0,0 @@ ---- -title: הצגת asynchronous JavaScript -slug: Learn/JavaScript/Asynchronous/Introducing -translation_of: Learn/JavaScript/Asynchronous/Introducing ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}}
- -

במאמר זה אנחנו נסקור שוב את הבעיות הקשורות ב-Synchronous JavaScript, ונסתכל לראשונה על הטכניקות לא-סינכרוניות שניתקל בהן, וכיצד הן יכולות לסייע לנו לפתור בעיות אלו.

- - - - - - - - - - - - -
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה:להבין מהי שAsynchronous JavaScript וכיצד היא שונה מ-Synchronous JavaScript, ומתי להשתמש בה.
- -

Synchronous JavaScript

- -

על מנת שנוכל להבין מה זה {{Glossary("asynchronous")}} JavaScript אנחנו צריכים תחילה להבין מה זה {{Glossary("synchronous")}} JavaScript. חלק זה של המאמר יסקור שוב חלק מהמידע שכבר עברנו עליו במאמר הקודם.

- -

הרבה מהפונקציונליות שראינו במודולים הקודמים של מדריך זה היו דיי סינכרוניים - אנחנו מריצים קוד מסויים והתוצאה של אותה ריצה מוחזרת כאשר הדפדפן יכול להחזיר את התוצאה. נסתכל כעת על דוגמא פשוטה ב-דף זהאו בקוד המקור:

- -
const btn = document.querySelector('button');
-btn.addEventListener('click', () => {
-  alert('You clicked me!');
-
-  let pElem = document.createElement('p');
-  pElem.textContent = 'This is a newly-added paragraph.';
-  document.body.appendChild(pElem);
-});
-
- -

בקוד זה, השורות מורצות אחת אחרי השנייה:

- -
    -
  1. אנחנו יוצרים הפנייה לאלמנט {{htmlelement("button")}} שכבר זמין ב-DOM.
  2. -
  3. אנחנו מוסיפים מטפל אירוע בשם click כך שכאשר הכפתור נלחץ: -
      -
    1. הודעת ()alert מוצגת למשתמש.
    2. -
    3. ברגע שהודעה זו נסגרת, אנחנו יוצרים אלמנט {{htmlelement("p")}}.
    4. -
    5. לאחר מכן אנחנו מכניסים לתוך האלמנט  {{htmlelement("p")}} תוכן.
    6. -
    7. בסוף אנחנו משייכים את ה- {{htmlelement("p")}} ל-body.
    8. -
    -
  4. -
- -

בעוד שכל תהליך שכזה נמצא בהרצה או עיבוד, שום דבר אחר לא יכול להתרחש - יתר העיבוד מושהה. זה מכיוון שכפי שראינו במאמר הקודם ש-JavaScript היא single threaded. רק דבר אחד יכול להתרחש בכל פעם על ה-single main thread, וכל היתר חסום לביצוע או לעיבוד עד אשר אותה פעולה תושלם.

- -

בדוגמא למעלה, אחרי שלחצנו על הכפתור, הפסקה לא הופיעה עד לאחר שכפתור ה-OK לא נלחץ בחלונית הקופצת. אתם יכולים לנסות זאת בעצמכם:

- - - -

{{EmbedLiveSample('Synchronous_JavaScript', '100%', '70px')}}

- -
-

לתשומת לב: חשוב לזכור שאמנם ()alert מאוד שימושי לשם הסבר על פעולות סינכרוניות שחוסמות את המשך הפעילות, זוהי פונקציה שאינה בשימוש רב ביישומים אמיתיים מטעמים של חווית משתמש לרוב.

-
- -

Asynchronous JavaScript

- -

לאור הסיבות שנסקרו למעלה, הרבה Web API משתמשים בקוד א-סינכרוני על מנת לפעול, במיוחד אלו שניגשים או מביאים משאב מסויים מגורם חיצוני, כמו הבאה של קובץ מהרשת, גישה למאגר מידע והחזרת מידע מתוכו, הפעלת של הזרמת וידאו באמצעות מצלמת רשת וכד׳.

- -

מדוע העבודה עם קוד א-סינכרוני היא מורכבת? נסתכל על דוגמא זריזה. כאשר אנחנו מבקשים תמונה משרת מסויים, איננו יכולים לקבל את התשובה באופן מיידי. זה אומר שהפסאודו-קוד הרשום להלן לא יעבוד:

- -
var response = fetch('myImage.png');
-var blob = response.blob();
-// display your image blob in the UI somehow
- -

זה מכיוון שאנחנו לא יודעים כמה זמן ייקח לתמונה להגיע מהשרת, אז כאשר אנחנו נרצה להריץ את שורת הקוד הבאה, היא תחזיר לנו שגיאה (אולי לסירוגין, אולי בכל פעם) מכיוון שה-response אינו זמין עבורנו עדיין. במקום זאת, אנחנו צריכים שהקוד שלנו יחכה ל-response שיוחזר אלינו לפני שאנחנו מנסים לעשות עם response פעולה כלשהי.

- -

יש שני סוגים עיקריים של קוד א-סינכרוני שאנחנו ניתקל בהם בקוד javascript, יש את ה-callbacks הותיקים ואת ה-promises החדשים יותר.  במאמר זה נסקור את שניהם.

- -

Async callbacks

- -

Async callbacks אלו פונקציות המועברות כפרמטר (ארגומנט) לפונקציה אחרת, כאשר אנחנו קוראים לפונקציה אחרת אשר מריצה קוד ברקע. כאשר הקוד שברקע סיים לרוץ, הוא קורא לאותן פונקציות callbacks על מנת לציין שהפעולה שהייתה ברקע הסתיימה או לציין שמשהו הסתיים.

- -

שימוש ב-callbacks יחסית נחשב מיושן כעת, אבל אנחנו עדיין נראה שימוש רב שלהם ב-APIs ישנים אבל עדיין מאוד שימושיים.

- -

דוגמא ל-async callback אפשר לראות בפרמטר השני של {{domxref("EventTarget.addEventListener", "addEventListener()")}} (כפי שראינו בפעולה למעלה):

- -
btn.addEventListener('click', () => {
-  alert('You clicked me!');
-
-  let pElem = document.createElement('p');
-  pElem.textContent = 'This is a newly-added paragraph.';
-  document.body.appendChild(pElem);
-});
- -

הפרמטר הראשון הוא הסוג של האירוע שאנחנו רוצים להאזין להתרחשות שלו, והפרמטר השני הוא פונקציית callback שמופעלת ברגע שהאירוע מתרחש.

- -

כאשר אנחנו מעבירים callback function כפרמטר לפונקציה אחרת, אנחנו רק מעבירים את הגדרת הפונקציה כפרמטר, כלומר ה-callback function לא מופעל באופן מיידי. הוא נקרא לאחר מכן (“called back”) באופן א-סינכרוני איפשהו בתוך הגוף של הפונקציה שקיבלה אותו כפרמטר. הפונקציה שקיבלה אותו כפרמטר היא האחראית להפעיל את ה-callback function כשנצטרך.

- -

אנחנו יכולים לכתוב פונקציות משלנו שיכילו callback function באופן דיי פשוט יחסית. נסתכל על דוגמא שמעלה משאב באמצעות XMLHttpRequest API (דף האינטרנט, ו- קוד המקור):

- -
function loadAsset(url, type, callback) {
-  let xhr = new XMLHttpRequest();
-  xhr.open('GET', url);
-  xhr.responseType = type;
-
-  xhr.onload = function() {
-    callback(xhr.response);
-  };
-
-  xhr.send();
-}
-
-function displayImage(blob) {
-  let objectURL = URL.createObjectURL(blob);
-
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-}
-
-loadAsset('coffee.jpg', 'blob', displayImage);
- -

כאן יצרנו את פונקציית ()displayImage שפשוט מקבלת blob שמועבר אליה ויוצרת לו URL באמצעות URL.createObjectURL(blob). לאחר מכן הפונקציה יוצרת אלמנט HTML מסוג img, משימה לו את הערך של ה-src לאותו URL שנוצר לנו ומשייכת את ה-image ל-body. 

- -

בנוסף, יצרנו פונקציה בשם ()loadAsset שמקבלת כפרמטרים כתובת URL, סוג הקובץ וכן פונקציית callback (שימו לב שהשם שנתנו לפרמטר - callback - הוא לשם הנוחות בלבד וניתן לקרוא לפרמטר זה בכל שם). פונקציית ()displayImage משתמשת ב-XMLHttpRequest (לרוב משתמשים בקיצור שלו - "XHR") על מנת להביא משאב מ-URL מסויים לפני שמעבירים את התגובה של אותה XMLHttpRequest לפונקציית callback שלנו - לפונקציית  ()displayImage.

- -

במקרה הזה, פונקציית ה-callback שלנו מחכה ש-XHR יסיים להוריד את המשאב שהוא הביא (באמצעות שימוש במטפל אירוע מסוג onload), וזאת לפני שהיא תקבל את המשאב.

- -

Callbacks הם מאוד ורסטיליים - לא רק שהם מאפשרים לנו לשלוט בסדר שבו פונקציות ירוצו ואיזה מידע יועבר ביניהן, הן גם מאפשרות לנו להעביר מידע לפונקציות שונות בהתאם לנסיבות. כך שאנחנו יכולים להריץ פעולות שונות על המשאב שהתקבל או התגובה שהתקבלה כמו processJSON(), displayText(), וכד׳. 

- -

שימו לב שלא כל ה-Callbacks הם א-סינכרוניים וחלקם הם סינכרוניים. כך לדוגמא, כאשר אנחנו משתמשים ב- {{jsxref("Array.prototype.forEach()")}} על מנת לעבור באמצעות לולאה על איברים במערך (ראו כדף אינטרנט, וכן את קוד המקור):

- -
const gods = ['Apollo', 'Artemis', 'Ares', 'Zeus'];
-
-gods.forEach(function (eachName, index){
-  console.log(index + '. ' + eachName);
-});
- -

בדוגמא זו, אנחנו עוברים על מערך של Greek gods ומדפיסים את מספרי האינדקס והערכים לקונסולה. הפרמטר שאנחנו נותנים ל-()forEach הוא פונקציית callback, אשר בעצמו מקבל שני פרמטרים, שם הפריט במערך ומספר האינדקס. יחד עם זאת, היא  לא מחכה לשום דבר, היא פשוט רצה באופן אוטומטי. 

- -

Promises

- -

Promises אלו בעצם הסגנון החדש לקוד א-סינכרוני שאנחנו נראה שמבוצע בהם שימוש ב-Web APIs מודרניים. דוגמא טובה לכך היא fetch() API, אשר הוא בעצם כמו גרסה מודרנית ויעילה יותר של {{domxref("XMLHttpRequest")}}. נסתכל על דוגמא מהמאמר שלנו בנושא הבאת מידע מהשרת אשר תגיעו אליו בהמשך:

- -
fetch('products.json').then(function(response) {
-  return response.json();
-}).then(function(json) {
-  products = json;
-  initialize();
-}).catch(function(err) {
-  console.log('Fetch problem: ' + err.message);
-});
- -
-

לתשומת לב: אתם יכולים למצוא את הגרסה הסופית ב- GitHub (ראו כאן את קוד המקור, וגם כדף אינטרנט).

-
- -

כאן אנחנו רואים ש-fetch() לוקח פרמטר אחד - את ה-URL של המשאב שנאחנו רוצים להביא מהרשת - והוא מחזיר promise. ה-promise היא בעצם אובייקט המייצג השלמה או כישלון של פעולת ה-שaysync. בצורה מסויימת, זו הדרך של הדפדפן להגיד ״אני מבטיח לחזור אליך עם תשובה ברגע שאוכל״. מכאן השם promise.

- -

צריך להתרגל לרעיון הזה על ידי תרגול. זה מרגיש קצת מוזר בהתחלה, כמו החתול של שרדינגר - {{interwiki("wikipedia", "Schrödinger's cat")}}. אף אחת מהאפשרויות לא קרתה עדיין, אז פעולת ההבאה - פעולת ה-fetch, כרגע מחכה לתוצאה של פעולת הדפדפן - להשלמה שלה בעתיד. לאחר מכן שיש לנו שלושה קודי בלוק שמשורשרים לסוף fetch():

- - - -
-

לתשומת לב: אתם תלמדו עוד הרבה על promises בהמשך המודול הזה, אז אל דאגה אם לא הבנתם אותם עד הסוף. זוהי רק סקירה.

-
- -

The event queue

- -

פעולות א-סינכרוניות כמו promises מושמות לתוך ה-event queue, אשר רץ לאחר שה-main thread סיים את העיבודים שלו, כך שהם לא יחסמו קוד JavaScript שבא אחריהם. הפעולות שב-promises יושלמו ברגע שיתאפשר, ויחזירו את התוצאה שלהן לסביבת הjavascript. Async operations like promises are put into an event queue, which runs after the main thread has finished processing so that they do not block subsequent JavaScript code from running. The queued operations will complete as soon as possible then return their results to the JavaScript environment.

- -

Promises מול callbacks

- -

ל-Promises יש קצת דמיון ל-callbacks הוותיקים. הם בעיקרון אבוייקט שהוחזר, אליו אנחנו מחברים פונקציות callbacks, ולא צריכים להעביר callbacks לתוך פונקציה.

- -

יחד עם זאת, promises נוצרו במיוחד עבור טיפול בפעולת א-סינכרוניות, ויש להם הרבה יתרונות על ה-callbacks הוותיקים:

- - - -

ההתנהגות של קוד א-סינכרוני

- -

בואו נעמיק בדוגמא שתסביר לנו יותר לעומק את ההתהנגות של קוד א-סינכרוני, שמראה מה יכול לקראת כשאנחנו לא בקיאים לגמי בסדר של הרצת הקוד וההבעיות שיש בניסיון לטפל בקוד א-סינכרוני כמו בקוד סינכרוני. הודמא הבא היא יחסית דומה למה שראינו בעבר. sכדף אינטרנט, וגם קוד המקור). הבדל אחד הוא שכללנו מספר ביטויים של {{domxref("console.log()")}} על ממנת להמחיש את הסדר שאנחנו נחשוב שבו הקוד ירוץ

- -
console.log ('Starting');
-let image;
-
-fetch('coffee.jpg').then((response) => {
-  console.log('It worked :)')
-  return response.blob();
-}).then((myBlob) => {
-  let objectURL = URL.createObjectURL(myBlob);
-  image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-}).catch((error) => {
-  console.log('There has been a problem with your fetch operation: ' + error.message);
-});
-
-console.log ('All done!');
- -

הדפדפן יתחיל להריץ את הקוד, הוא יראה את ה-console.log() הראשון ויריץ אותו. ולאחר מכן ייצור את המשתנה image .

- -

הוא לאחר מכן ימשיך לשורה הבאה, ויתחיל להריץ את הבלוק קוד של fetch(), אבל מכיוון ש-fetch() מורץ באופן א-סינכרוני בלי חסימה, הדפדפן ימשיך לקוד שלאחר הקוד של ה-promise-related code, ולכן יגיע ל-console.log() האחרון ( All done!) ואותו יציג לקונסולה. ימשיך לרוץ

- -

רק ברגע שהבלוק של ה-code>fetch() סיים לחלוטין לרוץ והביא תוצאה - result באמצעות הבלוקים של .then(), אנחנו נראה לבסוף את הההודעה שב-console.log() השני (It worked ;)). כך שההודעות הופיעו בסדר שונה ממה שאולי חשבתם:

- - - -

אם זה מבלבל אתכם, הסתכלו על הדוגמא הבאה:

- -
console.log("registering click handler");
-
-button.addEventListener('click', () => {
-  console.log("get click");
-});
-
-console.log("all done");
- -

זה מאוד דומה בהתנהגות - ה-console.log() הראשון והשלישי יציגו את ההודעות שלהן מיד, אבל ה-console.log() השני יהיה חסום להצגה עד אשר מישהו ילחץ על הכפתור. הדוגמא הקודמת פועלת בדרך דוה, למעט כך שבמקרה שההודעה השנייה חסומה בשרשרת ההבטחות המביאות משאב מסויים ומוצגת רק כאשר שרשרת ההבטטחות הושלמה, ולא כאשר המשתמש ילחץ על כפתור. .

- -

בדוגמה של קוד פחות טריוויאלי, קוד מהסוג של הדוגמא הראשונה עלולה לגרום לבעיה - אינכם יכולים לכלול בלוק קוד אסינכרוני המחזיר תוצאה, עליה אתם מסתמכים בהמשך בבלוק קוד סינכרוני. אינכם כולים להבטיח שפונקציית ה-שaysync תחזור לפני שהדפדפן יעבד את חסימת האסינכרון.

- -

על מנת לראות זאת בפעולה, נסו לעשות עותק מקומי של To see this in action, try taking a local copy of הדוגמאו תשלנו, ושנו את ה- console.log() שלישית כך:

- -
console.log ('All done! ' + image + 'displayed.');
- -

אתם אמורים לקבל שגיאה בקונסולה במקום ההודעה השלישית :

- -
TypeError: image is undefined; can't access its "src" property
- -

זה מכיוון שבזמן שהדפדפן מנסה להריץ את ה-console.log() השלישית, הבלוק קוד של fetch() עדיין לא סיים לרות, כך שהמשתנה image לא ניתן לו ערך עדיין.

- -

למידה עצמאית: פכו את הכל ל- async!

- -

על מנת לתקן את ה- fetch(), ולהפוך את שלושת -console.log() להיות מופעים בסדר הרצוי, אתם יכולים לעשות את ה-console.log() השלישי שירוץ גם הוא בצורה א-סינכרוני. את זה ניתן לעשות באמצעות העברה שלו לתוך .then() אחר, אשר משורשר לתוך הסוף של ה-.then() השני, או באמצעות פשוט העברה שלו לתוך ה-.then() השני. נסו לתקן זאת.

- -
-

לתשומת לב: אם נתקעתם, אתם יכולים למצוא את התשובה כאן או כ דף אינטרנט also). אתם גם יכולים למצוא עוד הרבה על promises במדריך שלנו בנושא טיפול בפעולות א-סינכרוניות באמצעות Promises, בהמשך המודול הזה.

-
- -

לסיכום

- -

במבנה הבסיסי שלה, JavaScript היא סינכרונית, שפה single-threaded,כך רק פעולה אחת יכולה להיות מעובדת בכל זמן נתון. יחד עם זאת, הדפדפנים הגדירו פונקציות ו-APIs שמאפשרים לנו לרשום פונקציות שלא ירוצו באופן סינכרוני, ובמקום זאת, יופעלו באופן א-סינכרוני כאשר אירוע מסויים מתרחש. זה אומר שאנחנו יכולים לתת לקוד שלנו לעשות דברים אחרים באותו הזמן, מבלי לחסום או לעצור את ה-main thread.

- -

בין אם אנחנו רוצים להירץ קוד באופן סינכרוני או א-סינכרוני, זה תלוי במה שאנחנו מנסים לעשות.

- -

יש פעמים שאנחנו נרצה שדברים יועלו ויתרחשו במיידי. לדוגמא, כאשר המתשמש מגדיר סגנון לאתר ואתם רוצים שהסגנון יוחל באופן מיידי.

- -

אם אנחנו מריצים פעולה מסויימת שלוקח לה זמן, כמו לדוגמא גישה למאגר מידע ושימוש בתוצאות על מנת ליצור תבניות לדגומא, זה יהיה עדיף להעביר את הפעולה הזו מחוץ ל-main thread, כך שתתצבע באופן א-סינכרוני. עם הזמן, אתם תלמדו מתי זה היה הגיוני לבחור בטכניקה א-סינכרונית ולא בסינכורנית.

- - - -

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}}

- -

במודול זה

- - diff --git a/files/he/learn/javascript/asynchronous/promises/index.html b/files/he/learn/javascript/asynchronous/promises/index.html deleted file mode 100644 index 87c8839084..0000000000 --- a/files/he/learn/javascript/asynchronous/promises/index.html +++ /dev/null @@ -1,589 +0,0 @@ ---- -title: Graceful asynchronous programming with Promises -slug: Learn/JavaScript/Asynchronous/Promises -translation_of: Learn/JavaScript/Asynchronous/Promises ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}
- -

Promises הן תכונה חדשה יחסית ב-JavaScript, אשר מאפשרת לנו לדחות פעולות מסוייומות עד אשר פעולותדמות להן יושלמו, או שיגיבו לכך שהן נכשלו. זוהי תכונה מאוד שימושית על מנת ליצור רצף של פעולות א-סינכרוניות שיעבדו בצור הטובה. מאמר זה נועד להסביר כיצד promises עובדות, כיצד אנו נראה אותם בשימוש ב-web APIs וכיצד נכתוב promises משלנו.

- - - - - - - - - - - - -
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה:להבין מהן promises וכיצד להשתמש בהן.
- -

מהן promises?

- -

סקרנו קצת Promises במאמר הראשון במודול זה, אבל במאמר זה נסקור אותן יותר לעומק.?

- -

בעיקרון promise הוא בעצם אובייקט שמייצג מצב ביניים של פעולה - בפועל, promise היא מעין הבטחה שתוצאה מסויימת תוחזר בנקודה מסויימת בעתיד. אין שום הבטחה מתי הפעולה תושלם ומתי התוצאה תוחזר, אבל יש הבטחה שכאשר התוצאה מוכנה, או שכאשר הפעוללה נכשלה, הקוד שסיפקנו ירוץ על מנת לעשות משהו עם תוצאה מוצלחת או להתמודד עם כשלון בפעולה.

- -

באופן כללי, אנחנו פחות מתעניינים בזמן שייקח לפעולה א-סינכרונית להחזיר את התוצאה שלה (אלא אם כן מדובר בזמן יותר מדי ארוך), ואנחנו יותר מעוניינים בכך שתהיה לנו אפשרות להגיב לאותה תגובה כאשר היא תחזור, לא משנה מהי התגובה. וכמובן, זה נחמד שאותה פעולה לא חוסמת את הקוד מלרוץ.

- -

אחד מהשימושים של promise שאנחנו נראה הוא ב-web APIs שמחזירים promise. נניח ויש לנו יישום וידאו צ׳אט. ליישום זה יש חלון עם רשימת החברים של המשתמש, ובלחיצה על כפתור ליד שם החבר, תחל שיחת וידאו עם אותו חבר.

- -

מטפל האירוע של הכפתור הזה קורא ל- {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} על מנת לקבל גישה למיקרופון ולמצלמה של המשתמש. מאחר ו-()getUserMedia חייב לוודא שלמשתמש יש אישור להשתמש באותם מכשירים ולבקש מהמשתמש לבחור איזה מיקרופון ואיזו מצלמה להשתמש בהם או בכל שילוב אחר. בזמן הבקשה הזו, פעולה זו יכולה לחסום את המשך התוכנית לא רק עד אשר כל האישורים האלו התקבלו, אלא גם עד אשר המצלמה והמיקרופון יתחברו. בנוסף, המשתמש אולי לא יגיב באופן מיידי לבקשות אלו. זה יכול לקחת הרבה זמן.

- -

מאחר והקריאה ל- ()getUserMedia נעשית מה- browser's main thread, הדפדפן חסום עד אשר ()getUserMedia תסיים. ברור כמובן שזו לא אפשרות מקובלת בימים אלו. ללא promises, כל דבר בדפדפן היה נהפך ללא שימושי עד אשר המשתמש יחליט מה לעשות עם המצלמה והמיקרופון. אז במקום לחכות למשתמש, לקבל את המכשירים שנבחרו, ולהחזיר את ה-{{domxref("MediaStream")}} שנוצר למקורות אלו, ()getUserMedia מחזיר {{jsxref("promise")}} אשר נפתר עם {{domxref("MediaStream")}} ברגע שהוא זמין.

- -

הקוד של יישום הוידאו צאט שלנו, עשוי להיראות כך?:?

- -
function handleCallButton(evt) {
-  setStatusMessage("Calling...");
-  navigator.mediaDevices.getUserMedia({video: true, audio: true})
-    .then(chatStream => {
-      selfViewElem.srcObject = chatStream;
-      chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream));
-      setStatusMessage("Connected");
-    }).catch(err => {
-      setStatusMessage("Failed to connect");
-    });
-}
-
- -

הפונקציה הזו מתחילה בכך שהיא משתמש בפונקציה שנקראת ()setStatusMessage על מנת לעדכן שורת עדכון למשתמש עם הטקסט: "Calling...", שמעידה על כך שמבוצע ניסיול החל בשיחה. לאחר מכן היא קוראת לפונקציה ()getUserMedia, ומבקשת שתחל בסטרים (stream) ?שיש לו גם וידאו וגם אודיו וברגע שהסטרים יהיה מוכן, היא ממשיכה בפעולות לשם הקמת הסטרים וחיבור המצלמה והאודיו. לאחר מכן היא מציגה למשתמש הודעה ״Connected״. 

- -

אם ()getUserMedia תיכשל, בלוק הקוד של catch ירוץ. הוא משתמש שוב ב- ()setStatusMessage על מנת להציג למשתמש שהתרחשה שגיאה. 

- -

הדבר החשוב כן הוא שהקריאה של ()getUserMedia מוחזרת כמעט באופן מיידי, גם אם הסטרים של המצלמה לא התקבל עדיין. אפילו אם הפונקציה של ()handleCallButton סיימה להריץ את הקוד שבתוכה והחזירה את השליטה לקוד שקרא לה, כאשר ()getUserMedia תסיים את הפעולה שלה, בין אם בהצלחה ובין אם תתרחש שגיאה, פונקציה זו תקרא שוב לאותו מטפל אירוע שסיפקנו לה. כלומר, היישום ימשיך לעבוד ולא יחכה לזרם הוידאו ולא ימנע מיתר הקוד להמשיך לרוץ. 

- -
-

לתשומת לב:  לפרטים נוספים אודות נושא מורכב זה של וידאו ואודיו, ראו Signaling and video calling.

-
- -

הבעיה עם callbacks

- -

על מנת להבין לעומק מדוע promises הן דבר טוב, יעזור לנו לחשוב על ה-callbacks המיושנות ולהבין מדוע הן בעייתיות. 

- -

ננסה להמחיש זאת באמצעות דוגמא להזמנת פיצה כאנלוגיה. יש מספר שלבים שאנחנו צריכים לעשות ולהשלים בהצלחה, אשר לא ממש הגיוני לבצע אותם בסדר אחר או לבצע אותם בסדר הנכון, אבל בלי לחכות שהשלב הקודם הסתיים:

- -
    -
  1. בחירת התוספות לפיצה - זה יכול לקחת זמן אם אנחנו לא ממש בטוחים איזו תוספת אנחנו רוצים על הפיצה ושלב זה יכול להיכשל אם בסופו של דבר לא קיבלנו החלטה איזו תוספת אנחנו רוצים, או אם בסוף החלטנו לאכול משהו אחר. 
  2. -
  3. בהנחה והחלטנו על תוספת, לאחר מכן אנחנו מבצעים הזמנה של הפיצה שאנחנו רוצים. שלב זה יכול לקחת זמן עד אשר הפיצה תהיה מוכנה, ואף יכול להיכשל אם לפיצרייה אין את המרכיבים הנכונים. 
  4. -
  5. בשלב האחרון אנחנו אוספים את הפיצה ואוכלים, גם שלב זה יכול להיכשל אם לא שילמנו לדוגמא על הפיצה או לא באנו לאסוף את הפיצה. 
  6. -
- -

עם ה-callbacks הישנות, קוד מופשט שלנו ייראה בערך כך: 

- -
chooseToppings(function(toppings) {
-  placeOrder(toppings, function(order) {
-    collectOrder(order, function(pizza) {
-      eatPizza(pizza);
-    }, failureCallback);
-  }, failureCallback);
-}, failureCallback);
- -

קוד זה הוא מבולגן וקשה להבנה, ולפעמים גם נקרא כ-callback hell, הוא גם דורש שהפונקציה ()failureCallback תיקרא כמה פעמים (בעבור כל פונקציה משורשרת) ויש לו גם חסרונות נוספים.

- -

שדרוג עם  promises

- -

Promises הופכות את סיטואציות כמו למעלה להרבה יותר פשוטות לכתיבה, פירוש וריצה. אם נציג את הקוד המופשט שלנו שוב באמצעות promises א-סינכרוניות, הוא ייראה כך:

- -
chooseToppings()
-.then(function(toppings) {
-  return placeOrder(toppings);
-})
-.then(function(order) {
-  return collectOrder(order);
-})
-.then(function(pizza) {
-  eatPizza(pizza);
-})
-.catch(failureCallback);
- -

זה כבר הרבה יותר טוב- הרבה יותר קל להבין מה קורה כאן והיינו צריכים רק בלוק קוד אחד של ()catch. בעבור כל השגיאות שאולי יתרחשו. כל הקוד הזה אינו חוסם את ה-main thread (כך שאנחנו יכולים להמשיך לראות טלווזיה עד אשר הפיצה תהיה מוכנה), וכל פעולה תחכה בוודאות עד אשר הפעולה הקודמת תסיים לפני שהיא תרוץ. אנחנו יכולים לקשור מספר פעולות א-סינכרוניות כך שיתרחשו אחת אחרי השנייה מכיוון שכל בלוק קוד של (.....)then. מחזיר promise חדשה, שנפתח כאשר הקוד שבתוך ה-(.....)then. הרלוונטי מסיים לרוץ. 

- -

באמצעות שימוש בפונקציות חץ (arrow functions), אנחנו אפילו יכולים להפוך את הקוד לעוד יותר פשוט: 

- - - -
chooseToppings()
-.then(toppings =>
-  placeOrder(toppings)
-)
-.then(order =>
-  collectOrder(order)
-)
-.then(pizza =>
-  eatPizza(pizza)
-)
-.catch(failureCallback);
- -

או אפילו בצורה הזו:

- -
chooseToppings()
-.then(toppings => placeOrder(toppings))
-.then(order => collectOrder(order))
-.then(pizza => eatPizza(pizza))
-.catch(failureCallback);
- -

זה עובד מכיוון שעם פונקציות חץ, x <= () הוא סינטקסס חוקי והוא קיצור של {return x} <= ().

- -

אנחנו אפילו יכולים לרשום את הקוד שלנו בצורה כזו, מאחר שהפונקציות רק מעביר את הארגומנטים שלהם בצורה ישירה, אין צורך באמת לשכבה נוספת של פונקציה:

- -
chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback);
- -

יחד עם זאת, סינטקס זה לא ניתן לשימוש שוב, ולא ממש ברור לקריאה. 

- -
-

לתשומת לב: אנחנו אפילו יכולים לעשות שיפורים נוספים בסינטקס באמצעות הסינטקס של async/await, אשר נסקור אותו בהמשך המודול.

-
- -

בבסיס שלהן, promises דומות למאזיני אירוע - event lisenters אך עם הבדלים ביניהם:

- - - -

הסבר של הסינטקט הבסיסי של promise

- -

Promises חשובות מאוד להבנה מכיוון שמרבית ה-Web API המודרניים משתמשים בהן בעבור פונקציות שעלולות לבצע פעולות ארוכות. 

- -

בהמשך המאמר הזה אנחנו נראה כיצד לכתוב promises משלנו, אבל כאן אנחנו נסכתל על דוגמאות פשוטות שאנחנו ניתקל בהן ב-Web API שונים.

- -

בדוגמא הראשונה שלנו, אנחנו נשתמש במתודת fetch(), על מנת להביא תמונה מהאינטרנט, במתודת {{domxref("Body.blob", "blob()")}} על מנת להמיר את התוכן הגולמי של התגובה שקיבלנו לאובייקט {{domxref("Blob")}} , ולאחר מכן נציג את אותו blob בתוך אלמנט {{htmlelement("img")}}. זהו מאוד דומה לדוגמא שהסתכלנו עליה במאמר הראשון במודול, אבל אנחנו נעשה את זה מעט שונה כך שאתם תבנו את ה-promise. 

- -
    -
  1. -

    ראשית, הורידו את ה-HTML template ואת ה-image file שאנחנו נייבא. 

    -
  2. -
  3. -

    הוסיפו אלמנט {{htmlelement("script")}} בתחתית ה-{{htmlelement("body")}} בקובץ ה-HTML.

    -
  4. -
  5. -

    בתוך האלמנט {{HTMLElement("script")}} , הוסיפו את השורה הבאה: 

    -
  6. -
  7. -
    let promise = fetch('coffee.jpg');
    - -

    שורה זו קוראת למתודת ()fetch ומעבירה אליה כפרמטר את ה-URL של התמונה שאנחנו רוצים לייבא מהרשת. אנחנו מאחסנים את אובייקט ה-promise שיוחזר אלינו מ-()fetch בתוך משתנה שנקרא לו promise. כפי שאמרנו בעבר, האובייקט הזה מייצג מצב ביניים שבהתחלה הוא לא הצלחה ולא כישלון - מצב זה נקרא pending.

    -
  8. -
  9. על מנת להגיב להצלחה של הפעולה כאשר היא תקרה, במקרה הזה כאשר {{domxref("Response")}} תוחזר אלינו, אנחנו נפעיל את המתודת ()then. של אובייקט ה-promise. ה-callback בתוך בלוק הקוד של ()then. (שנקרא גם executor), ירוץ רק כאשר פעולת ה-promise תושלם בהצלחה ותחזיר אובייקט {{domxref("Response")}} - במונחי promise, כאשר ה-promise תגיע למצב של הושלמה, fulfilled. היא תעביר את האובייקט {{domxref("Response")}} כפרמטר. 
  10. -
  11. -
    -

    לתשומת לב: הדרך שבה הבלוק ()then. עובד היא דומה לדרך שבה אנחנו מוסיפים מאזין אירוע - event listener - לאובייקט באמצעות המתודה ()AddEventListener. מאזין האירוע לא ירוץ עד אשר האירוע יתרחש (ובאותה נשימה, כאשר ה-promise הושלמה בהצלחה). ההבדל העיקרי ביניהם הוא ש-()then. ירוץ רק פעם אחת בכל פעם שמשתמשים בו ואילו מאזין האירוע יכול להיות מופעל כמה פעמים. 

    -
    - -

    אנחנו מייד נריץ את מתודת  ()blob על התגובה הזו, על מנת לוודא שגוף התגובה הורד בהצלחה, וכאשר הוא זמין נהפוך אותו לאובייקט Blob שאנחנו יכולים לעשות איתו משהו. התוצאה של זה תוחזר לנו כך :

    - -
    response => response.blob()
    - -

    שזה קיצור של: 

    - -
    function(response) {
    -  return response.blob();
    -}
    - -

    עד כאן עם ההסבר, אנא הוסיפו את הקוד הבא מתחת לשורה הראשונה של JavaScript: 

    - -
    let promise2 = promise.then(response => response.blob());
    -
  12. -
  13. -

    כל קריאה ל-()then. יוצרת promise חדשה. זהו מאוד שימושי - מכיוון שמתודת -  ()blob מחזירה גם היא promise, אנחנו יכולים לטפל באובייקט ה-Blob שהיא מחזירה בעת ההשלמה שלו באמצעות הפעלה של מתודת ()then. על ה-promise השנייה. מכיוון שאנחנו רוצים לעשות משהו קצת יותר מורכב לאותו blob מאשר רק להריץ מתודה אחת עליו ולהחזיר את התוצאה, אנחנו צריכים לעטוף את גוף הפונקצייה בסוגריים מסולסלות - אחרת זה יגרום לשגיאה. הוסיפו את השורה הבאה מתחת לקוד הנוכחי שלכם: 

    -
  14. -
  15. -
    let promise3 = promise2.then(myBlob => {
    -
    -})
    -
  16. -
  17. -

    כעת, נכניס את הקוד הבא שהוא הפונקציה שתופעל, לתוך הסוגריים המסולסלות:

    - -
    let objectURL = URL.createObjectURL(myBlob);
    -let image = document.createElement('img');
    -image.src = objectURL;
    -document.body.appendChild(image);
    - -

    מה שעשינו כאן אנחנו מריצים בעצם מריצים מתודת {{domxref("URL.createObjectURL()")}} , מעבירים אליה כפרמרט את ה-Blob שהוחזר אלינו כאשר ה-promise השנייה הושלמה. זה מחזיר לנו URL שמצביע על האובייקט. לאחר מכן יצרנו אלמנט {{htmlelement("img")}} , וקבענו את ה-src שלו שיהיה שווה ל-URL של האובייקט ושייכנו אותו ל-DOM, כך שהתמונה תוצג על גבי הדף. 

    -
  18. -
- -

אם תשמרו ותרעננו את הדף, אתם תראו שהתמונה מוצגת על גבי הדף. 

- -
-

לתשומת לב:  אתם בטח תשימו לב שדוגמאות אלו ארוכות מדי בשביל פעולה פשוטה שיכולנו לבצע באמצעות יצירת אלמנט <img> וקביעת ה-src שלו לאותו URL של התמונה במקום לעשות זאת באמצעות ()fetch ובאמצעות ()blob. יחד עם זאת, דוגמא זו נועדה על מנת להסביר בפשטות את תהליך ה-promises.

-
- -

תגובה לכישלון 

- -

יש משהו חסר בדוגמא שלנו - כרגע, אין משהו שמגדיר כיצד להתמודד עם שגיאה כאשר ה-promise נכשלת, או rejects במונחים של promises. אנחנו יכולים להוסיף טיפול בשגיאה באמצעות הרצת מתודת ()catch. של ה-promise הקודמת:

- -
let errorCase = promise3.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- - - -

To see this in action, try misspelling the URL to the image and reloading the page. The error will be reported in the console of your browser's developer tools.

- -

This doesn't do much more than it would if you just didn't bother including the .catch() block at all, but think about it — this allows us to control error handling exactly how we want. In a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever.

- -
-

Note: You can see our version of the example live (see the source code also).

-
- -

Chaining the blocks together

- -

This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then() blocks (and also .catch() blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub):

- -
fetch('coffee.jpg')
-.then(response => response.blob())
-.then(myBlob => {
-  let objectURL = URL.createObjectURL(myBlob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-})
-.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- -

Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then() block's executor function.

- -
-

Note: .then()/.catch() blocks in promises are basically the async equivalent of a try...catch block in sync code. Bear in mind that synchronous try...catch won't work in async code.

-
- -

Promise terminology recap

- -

There was a lot to cover in the above section, so let's go back over it quickly to give you a short guide that you can bookmark and use to refresh your memory in the future. You should also go over the above section again a few more time to make sure these concepts stick.

- -
    -
  1. When a promise is created, it is neither in a success or failure state. It is said to be pending.
  2. -
  3. When a promise returns, it is said to be resolved. -
      -
    1. A successfully resolved promise is said to be fulfilled. It returns a value, which can be accessed by chaining a .then() block onto the end of the promise chain. The executor function inside the .then() block will contain the promise's return value.
    2. -
    3. An unsuccessful resolved promise is said to be rejected. It returns a reason, an error message stating why the promise was rejected. This reason can be accessed by chaining a .catch() block onto the end of the promise chain.
    4. -
    -
  4. -
- -

Running code in response to multiple promises fulfilling

- -

The above example showed us some of the real basics of using promises. Now let's look at some more advanced features. For a start, chaining processes to occur one after the other is all fine, but what if you want to run some code only after a whole bunch of promises have all fulfilled?

- -

You can do this with the ingeniously named Promise.all() static method. This takes an array of promises as an input parameter and returns a new Promise object that will fulfill only if and when all promises in the array fulfill. It looks something like this:

- -
Promise.all([a, b, c]).then(values => {
-  ...
-});
- -

If they all fulfill, then chained .then() block's executor function will be passed an array containing all those results as a parameter. If any of the promises passed to Promise.all() reject, the whole block will reject.

- -

This can be very useful. Imagine that we’re fetching information to dynamically populate a UI feature on our page with content. In many cases, it makes sense to receive all the data and only then show the complete content, rather than displaying partial information.

- -

Let's build another example to show this in action.

- -
    -
  1. -

    Download a fresh copy of our page template, and again put a <script> element just before the closing </body> tag.

    -
  2. -
  3. -

    Download our source files (coffee.jpg, tea.jpg, and description.txt), or feel free to substitute your own.

    -
  4. -
  5. -

    In our script we'll first define a function that returns the promises we want to send to Promise.all(). This would be easy if we just wanted to run the Promise.all() block in response to three fetch() operations completing. We could just do something like:

    - -
    let a = fetch(url1);
    -let b = fetch(url2);
    -let c = fetch(url3);
    -
    -Promise.all([a, b, c]).then(values => {
    -  ...
    -});
    - -

    When the promise is fulfilled, the values passed into the fullfillment handler would contain three Response objects, one for each of the fetch() operations that have completed.

    - -

    However, we don't want to do this. Our code doesn't care when the fetch() operations are done. Instead, what we want is the loaded data. That means we want to run the Promise.all() block when we get back usable blobs representing the images, and a usable text string. We can write a function that does this; add the following inside your <script> element:

    - -
    function fetchAndDecode(url, type) {
    -  return fetch(url).then(response => {
    -    if (type === 'blob') {
    -      return response.blob();
    -    } else if (type === 'text') {
    -      return response.text();
    -    }
    -  })
    -  .catch(e => {
    -    console.log('There has been a problem with your fetch operation: ' + e.message);
    -  });
    -}
    - -

    This looks a bit complex, so let's run through it step by step:

    - -
      -
    1. First of all we define the function, passing it a URL and a string representing the type of resource it is fetching.
    2. -
    3. Inside the function body, we have a similar structure to what we saw in the first example — we call the fetch() function to fetch the resource at the specified URL, then chain it onto another promise that returns the decoded (or "read") response body. This was always the blob() method in the previous example.
    4. -
    5. However, two things are different here: -
        -
      • First of all, the second promise we return is different depending on what the type value is. Inside the executor function we include a simple if ... else if statement to return a different promise depending on what type of file we need to decode (in this case we've got a choice of blob or text, but it would be easy to extend this to deal with other types as well).
      • -
      • Second, we have added the return keyword before the fetch() call. The effect this has is to run the entire chain and then run the final result (i.e. the promise returned by blob() or text()) as the return value of the function we've just defined. In effect, the return statements pass the results back up the chain to the top.
      • -
      -
    6. -
    7. -

      At the end of the block, we chain on a .catch() call, to handle any error cases that may come up with any of the promises passed in the array to .all(). If any of the promises reject, the catch block will let you know which one had a problem. The .all() block (see below) will still fulfill, but just won't display the resources that had problems. If you wanted the .all to reject, you'd have to chain the .catch() block on to the end of there instead.

      -
    8. -
    - -

    The code inside the function body is async and promise-based, therefore in effect the entire function acts like a promise — convenient.

    -
  6. -
  7. -

    Next, we call our function three times to begin the process of fetching and decoding the images and text, and store each of the returned promises in a variable. Add the following below your previous code:

    - -
    let coffee = fetchAndDecode('coffee.jpg', 'blob');
    -let tea = fetchAndDecode('tea.jpg', 'blob');
    -let description = fetchAndDecode('description.txt', 'text');
    -
  8. -
  9. -

    Next, we will define a Promise.all() block to run some code only when all three of the promises stored above have successfully fulfilled. To begin with, add a block with an empty executor inside the .then() call, like so:

    - -
    Promise.all([coffee, tea, description]).then(values => {
    -
    -});
    - -

    You can see that it takes an array containing the promises as a parameter. The executor will only run when all three promises resolve; when that happens, it will be passed an array containing the results from the individual promises (i.e. the decoded response bodies), kind of like [coffee-results, tea-results, description-results].

    -
  10. -
  11. -

    Last of all, add the following inside the executor. Here we use some fairly simple sync code to store the results in separate variables (creating object URLs from the blobs), then display the images and text on the page.

    - -
    console.log(values);
    -// Store each value returned from the promises in separate variables; create object URLs from the blobs
    -let objectURL1 = URL.createObjectURL(values[0]);
    -let objectURL2 = URL.createObjectURL(values[1]);
    -let descText = values[2];
    -
    -// Display the images in <img> elements
    -let image1 = document.createElement('img');
    -let image2 = document.createElement('img');
    -image1.src = objectURL1;
    -image2.src = objectURL2;
    -document.body.appendChild(image1);
    -document.body.appendChild(image2);
    -
    -// Display the text in a paragraph
    -let para = document.createElement('p');
    -para.textContent = descText;
    -document.body.appendChild(para);
    -
  12. -
  13. -

    Save and refresh and you should see your UI components all loaded, albeit in a not particularly attractive way!

    -
  14. -
- -

The code we provided here for displaying the items is fairly rudimentary, but works as an explainer for now.

- -
-

Note: If you get stuck, you can compare your version of the code to ours, to see what it is meant to look like — see it live, and see the source code.

-
- -
-

Note: If you were improving this code, you might want to loop through a list of items to display, fetching and decoding each one, and then loop through the results inside Promise.all(), running a different function to display each one depending on what the type of code was. This would make it work for any number of items, not just three.

- -

In addition, you could determine what the type of file is being fetched without needing an explicit type property. You could for example check the {{HTTPHeader("Content-Type")}} HTTP header of the response in each case using response.headers.get("content-type"), and then react accordingly.

-
- -

Running some final code after a promise fulfills/rejects

- -

There will be cases where you want to run a final block of code after a promise completes, regardless of whether it fulfilled or rejected. Previously you'd have to include the same code in both the .then() and .catch() callbacks, for example:

- -
myPromise
-.then(response => {
-  doSomething(response);
-  runFinalCode();
-})
-.catch(e => {
-  returnError(e);
-  runFinalCode();
-});
- -

In more recent modern browsers, the .finally() method is available, which can be chained onto the end of your regular promise chain allowing you to cut down on code repetition and do things more elegantly. The above code can now be written as follows:

- -
myPromise
-.then(response => {
-  doSomething(response);
-})
-.catch(e => {
-  returnError(e);
-})
-.finally(() => {
-  runFinalCode();
-});
- -

For a real example, take a look at our promise-finally.html demo (see the source code also). This works exactly the same as the Promise.all() demo we looked at in the above section, except that in the fetchAndDecode() function we chain a finally() call on to the end of the chain:

- -
function fetchAndDecode(url, type) {
-  return fetch(url).then(response => {
-    if(type === 'blob') {
-      return response.blob();
-    } else if(type === 'text') {
-      return response.text();
-    }
-  })
-  .catch(e => {
-    console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
-  })
-  .finally(() => {
-    console.log(`fetch attempt for "${url}" finished.`);
-  });
-}
- -

This logs a simple message to the console to tell us when each fetch attempt has finished.

- -
-

Note: finally() allows you to write async equivalents to try/catch/finally in async code.

-
- -

Building your own custom promises

- -

The good news is that, in a way, you've already built your own promises. When you've chained multiple promises together with .then() blocks, or otherwise combined them to create custom functionality, you are already making your own custom async promise-based functions. Take our fetchAndDecode() function from the previous examples, for example.

- -

Combining different promise-based APIs together to create custom functionality is by far the most common way you'll do custom things with promises, and shows the flexibility and power of basing most modern APIs around the same principle. There is another way, however.

- -

Using the Promise() constructor

- -

It is possible to build your own promises using the Promise() constructor. The main situation in which you'll want to do this is when you've got code based on an an old-school asynchronous API that is not promise-based, which you want to promis-ify. This comes in handy when you need to use existing, older project code, libraries, or frameworks along with modern promise-based code.

- -

Let's have a look at a simple example to get you started — here we wrap a setTimeout() call with a promise — this runs a function after two seconds that resolves the promise (using the passed resolve() call) with a string of "Success!".

- -
let timeoutPromise = new Promise((resolve, reject) => {
-  setTimeout(function(){
-    resolve('Success!');
-  }, 2000);
-});
- -

resolve() and reject() are functions that you call to fulfill or reject the newly-created promise. In this case, the promise fulfills with a string of "Success!".

- -

So when you call this promise, you can chain a .then() block onto the end of it and it will be passed a string of "Success!". In the below code we simply alert that message:

- -
timeoutPromise
-.then((message) => {
-   alert(message);
-})
- -

or even just

- -
timeoutPromise.then(alert);
-
- -

Try running this live to see the result (also see the source code).

- -

The above example is not very flexible — the promise can only ever fulfill with a single string, and it doesn't have any kind of reject() condition specified (admittedly, setTimeout() doesn't really have a fail condition, so it doesn't matter for this simple example).

- -
-

Note: Why resolve(), and not fulfill()? The answer we'll give you for now is it's complicated.

-
- -

Rejecting a custom promise

- -

We can create a promise that rejects using the reject() method — just like resolve(), this takes a single value, but in this case it is the reason to reject with, i.e., the error that will be passed into the .catch() block.

- -

Let's extend the previous example to have some reject() conditions as well as allowing different messages to be passed upon success.

- -

Take a copy of the previous example, and replace the existing timeoutPromise() definition with this:

- -
function timeoutPromise(message, interval) {
-  return new Promise((resolve, reject) => {
-    if (message === '' || typeof message !== 'string') {
-      reject('Message is empty or not a string');
-    } else if (interval < 0 || typeof interval !== 'number') {
-      reject('Interval is negative or not a number');
-    } else {
-      setTimeout(function(){
-        resolve(message);
-      }, interval);
-    }
-  });
-};
- -

Here we are passing two arguments into a custom function — a message to do something with, and the time interval to pass before doing the thing. Inside the function we then return a new Promise object — invoking the function will return the promise we want to use.

- -

Inside the Promise constructor, we do a number of checks inside if ... else structures:

- -
    -
  1. First of all we check to see if the message is appropriate for being alerted. If it is an empty string or not a string at all, we reject the promise with a suitable error message.
  2. -
  3. Next, we check to see if the interval is an appropriate interval value. If it is negative or not a number, we reject the promise with a suitable error message.
  4. -
  5. Finally, if the parameters both look OK, we resolve the promise with the specified message after the specified interval has passed using setTimeout().
  6. -
- -

Since the timeoutPromise() function returns a Promise, we can chain .then(), .catch(), etc. onto it to make use of its functionality. Let's use it now — replace the previous timeoutPromise usage with this one:

- -
timeoutPromise('Hello there!', 1000)
-.then(message => {
-   alert(message);
-})
-.catch(e => {
-  console.log('Error: ' + e);
-});
- -

When you save and run the code as is, after one second you'll get the message alerted. Now try setting the message to an empty string or the interval to a negative number, for example, and you'll be able to see the promise reject with the appropriate error messages! You could also try doing something else with the resolved message rather than just alerting it.

- -
-

Note: You can find our version of this example on GitHub as custom-promise2.html (see also the source code).

-
- -

A more real-world example

- -

The above example was kept deliberately simple to make the concepts easy to understand, but it is not really very async. The asynchronous nature is basically faked using setTimeout(), although it does still show that promises are useful for creating a custom function with sensible flow of operations, good error handling, etc.

- -

One example we'd like to invite you to study, which does show a useful async application of the Promise() constructor, is Jake Archibald's idb library. This takes the IndexedDB API, which is an old-style callback-based API for storing and retrieving data on the client-side, and allows you to use it with promises. If you look at the main library file you'll see the same kind of techniques we discussed above being used there. The following block converts the basic request model used by many IndexedDB methods to use promises:

- -
function promisifyRequest(request) {
-  return new Promise(function(resolve, reject) {
-    request.onsuccess = function() {
-      resolve(request.result);
-    };
-
-    request.onerror = function() {
-      reject(request.error);
-    };
-  });
-}
- -

This works by adding a couple of event handlers that fulfill and reject the promise at appropriate times:

- - - -

Conclusion

- -

Promises are a good way to build asynchronous applications when we don’t know the return value of a function or how long it will take to return. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous try...catch statement.

- -

Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.

- -

We didn't touch on all promise features in this article, just the most interesting and useful ones. As you start to learn more about promises, you'll come across further features and techniques.

- -

Most modern Web APIs are promise-based, so you'll need to understand promises to get the most out of them. Among those APIs are WebRTC, Web Audio API, Media Capture and Streams, and many more. Promises will be more and more important as time goes on, so learning to use and understand them is an important step in learning modern JavaScript.

- -

See also

- - - -

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}

- -

במודול זה

- - diff --git a/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html b/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html deleted file mode 100644 index 2d97d2827d..0000000000 --- a/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html +++ /dev/null @@ -1,651 +0,0 @@ ---- -title: 'Cooperative asynchronous JavaScript: Timeouts and intervals' -slug: Learn/JavaScript/Asynchronous/Timeouts_and_intervals -translation_of: Learn/JavaScript/Asynchronous/Timeouts_and_intervals ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}
- -

- במאמר זה אנחנו נסתכל על מתודות מסורתיות שיש ב-JavaScript, בעבור הרצה של קוד באופן א-סינכרוני לאחר שזמן מסויים עבר או באינטרוול מסויים (כלומר לקבוע מספר פעמים שירוץ בכל פרק זמן מסויים), נדון בשימושים שלהם ומה הסוגיות הטבועות בהם. - -

- - - - - - - - - - - - -
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה: - הבנה של לולאות א-סינכרוניות ואינטרוולים ולמה הם משמים.
- -

הקדמה

- -

- במשך זמן רב, פלטפורמת ה-web העניקה למפתחי JavaScript מספר של פונקציות שאפשרו לה להריץ קוד באופן א-סינכרוני, כך שהקוד ירוץ לאחר זמן מסויים שעבר או להריץ קוד מסויים באופן א-סינכרוני,ע ם הפרש זמן מסויים בין כל ריצה שלו, עד שאנחנו נגיד לו לעצור. אלו הם :

- -
-
setTimeout()
-
- מריץ בלוק קוד מסויים פעם אחת לאחר שזמן מסויים עבר.
-
setInterval()
-
- מריץ בלוק קוד מסויים באופן חוזר, עם הפרש של זמן מסויים בין כל ריצה.
-
requestAnimationFrame()
-
- זוהי גרסה מודרנית ל-setInterval(). היא מריצה בלוק קוד מסויים לפני שהדפדפן צובע מחדש את התצוגה, כך שמתאפשרת לאניממציה לרוץ במסגרת מתאימה ללא קשר לסביבה בה היא פועלת. -
-
- -

- הקוד הא-סינכרוני שנכתב באמצעות פונקציות אלו בעצם ירוץ על ה-00000, אבל כן התאפשר לנו להריץ קוד אחר בין כל ריצה שלהם במידה מסוייתמ, תלוי כמה הפונקציות שנכתוב יעשו שימוש רב במעבד. בכל מקרה, הפונקציות הללו משמשות אנימציות קבועות ועוד תהליכי רקע על אתר אינטרנט או יישום אינטרנטר. בחלקים הבאים של המאמר אנחנו נגע בכל אחת מהן ולמה הן משמשות. .

- -

setTimeout()

- -

- כפי שאמרנו למעלה, setTimeout() מריצה בלוק קוד מסויים פעם אחת, לאחר שזמן מסויים שהגדרנו לה חלף. היא מקבלת את הפרמטרים הבאים:

- - - -
-

לתשומת לב: - מכיוון ש-0000000 מורצות ביחד, אין כל הבטחה שהן יופעלו במדוייק לאחר הזמן שהגדרנו. במקום, הם ייקראו לאחר שהזמן שהגדרנו חלף, לפחות. - - Because timeout callbacks are executed cooperatively, there's no guarantee that they will be called after exactly the specified amount of time. Instead, they will be called after at least that much time has elapsed. - - - Timeout handlers לא יכולים לרוץ עד אשר ה-main thread מגיע לנקודה בריצה שלו שם הוא עובר על מטפלים אלו למצוא את אלו שהוא צריך להריץ אותם. שה-00000 -

-
- -

- בדוגמא הבאה, הדפדפן יחכה שתי שניות לפני שיריץ את הפונקציה האנונימית, ואז יציג את הודעת ה-alert. -e (ראו כדף אינטרנט, וכן את קוד המקור):

- -
let myGreeting = setTimeout(function() {
-  alert('Hello, Mr. Universe!');
-}, 2000)
- -

- הפונקציות שאנחנו מציינים לא חייבות להיות אנונימיות. אנחנו יכולים לתת לפונקציה שלנו שם ואפילו להגדיר אותה במקום אחר, ואז להעביר הפנייה לפונקציה בתוך ה- setTimeout() . הגרסאות הבאות של הקוד שלנו הם שוות לראשונה: - - he functions we specify don't have to be anonymous. We can give our function a name, and can even define it somewhere else and pass a function reference to the setTimeout(). The following two versions of our code snippet are equivalent to the first one:

- -
// With a named function
-let myGreeting = setTimeout(function sayHi() {
-  alert('Hello, Mr. Universe!');
-}, 2000)
-
-// With a function defined separately
-function sayHi() {
-  alert('Hello Mr. Universe!');
-}
-
-let myGreeting = setTimeout(sayHi, 2000);
- -

- זה יכול להיות שימושי כאשר יש לנו פונקציה שצריכה להיקרא/להיות מופעלת גם מתוך -timeout וגם בתגובה לאירוע, לדוגמא. אבל, זה גם יכול לעזור לנו להשאיר את הקוד שלנו מסודר, במיוחד אם אחרי ה-timeout callback יש לנו יותר מכמה שורות קוד. -

- -

setTimeout() - מחזירה ערך מזהה שיכול לשמש לשם הפנייה לאותו timeout לאחר מכן, אם נרצה לדוגמא לעצור את ה-timeout. ראו {{anch("Clearing timeouts")}} בהמשך על מנת ללמוד כיצד לעשות זאת. - - -

- -

העברת פרמטרים לפונקציית setTimeout()

- -

- כל פרמטר שנרצה להעביר לפונקציה שתרוף בתוך ה-setTimeout(), יהיו חייבים להיות מועברים כפרמטרים נוספוים לפונקציית ה-setTimeout(), וזאת בסוף הרשימת פרמטרים. לדוגמא, אנחנו יכולים כתוב מחדש את הפונקציה הקודמת שלנו כך שהיא תגיד hi לכל שם שיועבר אליה -:

- -
function sayHi(who) {
-  alert('Hello ' + who + '!');
-}
- -

- השם של ה-person יכול להיות מועבר כפרמטר שלישי לתוך ה-setTimeout() - -:

- -
let myGreeting = setTimeout(sayHi, 2000, 'Mr. Universe');
- -

מחיקת Timeouts

- -

- לבסוף, אם timeout נוצר, אנחנו יכולים לבטל אותו לפני שהזמן שהגדרנו לו הסתיים באמצעשות שימוש ב-clearTimeout() והעברה של אותו ערך מזהה של ה-setTimeout() כפרמטר. כך, על מנת לבטל את ה-setTimeout() בדוגמא למעלה, אנחנו צריכים לרשום משהו כזה: -

- -
clearTimeout(myGreeting);
- -
-

לתשומת לב: ראו greeter-app.html - לדוגמא יותר מעניינת אשר מאפשרת לכן לקבוע את השם של האדם שנגיד לו שלום בטופס, ואז לבטל את הברכה באמצעו תכפתור אחג. (קוד המקור).

-
- -

setInterval()

- -

setTimeout() עובדת מצוים כאשר אנחנו צריכים להריץ בלוק קוד מסויים פעם אחת לאחר אינטרוול זמן שעבר. אבל מה קורה כאשר אנחנו רוצים להריץ קוד מסויים שוב ושוב, כמו במקרה של אנימציות?

- -

כאן נכנס לתמונה setInterval() . - פונקציה זו עובדת בצורה דומה ל-setTimeout(), למעט העובדה שהפונקציה שאנחנו מעבירים כפרמטר ראשון, תרוץ באופן חוזר ונשנה לכל הפחות בכל משך הזמן שהוגדר לה (גם כן במילישניות), ולא רק פעם אחת. אנחנו גם יכולים להעביר לה את הפרמטרים הדרושים לפונקציה שתרוץ. -.

- -

- נראה דוגמא על מנת להמחיש את העניין. הפונקציה הבא יוצרת אובייקט Date() חדש, מחלצת חרוזת זמן מתוכו באמצעות שימוש ב- toLocaleTimeString() ציגה את זה לממשק המתשמש. לאחר מכן אנחנו מריצים פונקציה אחת לשנייה באמצעות שימוש ב-setInterval() - על מנת ליצור את האפשר של שעון דיגיטלי שמעדכן את עצמו כל שנייה. - (ראו כדף אינטרנט, ואת also קוד המקור):

- -
function displayTime() {
-   let date = new Date();
-   let time = date.toLocaleTimeString();
-   document.getElementById('demo').textContent = time;
-}
-
-const createClock = setInterval(displayTime, 1000);
- -

בדיוק כמו setTimeout(), setInterval() מחזירה ערך מזהה כך שאנחנו יכולים להשתמש בו בהמשך על מנת למחוק את ה-interval.

- -

מחיקת intervals

- -

setInterval() תמשיך לרוץ באופן מתמשך וקבוע, אלא אם אנחנו נעשה איתה משהו - - אנחנו נרצה אולי דרך לעצור משימות כאלו, אחרת אנחנו נקבל שגיאות השהדפדפן לא מצליח להשלים גרסאות נוספות של המשימה הזו, או שהאניממציה שמטופלת על ידי המשימה הזו הסתיימה. אנחנו יכולים לעשות זאת באותה דרך שבה אנחנו מסיימים setInterval() - באמצעות העבר הערך המזהה שהוחזר לנו בהפעלה של setInterval() לפונקציה clearInterval(): - -

- -
const myInterval = setInterval(myFunction, 2000);
-
-clearInterval(myInterval);
- -

למידה עצמאית: יצירה של שעון עצר

- -

לאחר שעברנו על פונקציות אלו, נסו לאתגר את עצמכם במשימה זו. עשו עותקשל הדוגמא שלנו שנמצא ב- setInterval-clock.html ושנו אותה כך שתהיה שעון סטופר.

- -

- אתם צריכים להציג את הזמן כמו בדוגמא הקודמת, רק שבתרגיל זה אתם תצטרכו:

- - - -

רמזים:

- - - -
-

Note: If you get stuck, you can find our version here (see the source code also).

-
- -

Things to keep in mind about setTimeout() and setInterval()

- -

There are a few things to keep in mind when working with setTimeout() and setInterval(). Let's review these now.

- -

Recursive timeouts

- -

There is another way we can use setTimeout(): We can call it recursively to run the same code repeatedly, instead of using setInterval().

- -

The below example uses a recursive setTimeout() to run the passed function every 100 milliseconds:

- -
let i = 1;
-
-setTimeout(function run() {
-  console.log(i);
-  i++;
-  setTimeout(run, 100);
-}, 100);
- -

Compare the above example to the following one — this uses setInterval() to accomplish the same effect:

- -
let i = 1;
-
-setInterval(function run() {
-  console.log(i);
-  i++
-}, 100);
- -

How do recursive setTimeout() and setInterval() differ?

- -

The difference between the two versions of the above code is a subtle one.

- - - -

When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get errors.

- -

Immediate timeouts

- -

Using 0 as the value for setTimeout() schedules the execution of the specified callback function as soon as possible but only after the main code thread has been run.

- -

For instance, the code below (see it live) outputs an alert containing "Hello", then an alert containing "World" as soon as you click OK on the first alert.

- -
setTimeout(function() {
-  alert('World');
-}, 0);
-
-alert('Hello');
- -

This can be useful in cases where you want to set a block of code to run as soon as all of the main thread has finished running — put it on the async event loop, so it will run straight afterwards.

- -

Clearing with clearTimeout() or clearInterval()

- -

clearTimeout() and clearInterval() both use the same list of entries to clear from. Interestingly enough, this means that you can use either method to clear a setTimeout() or setInterval().

- -

For consistency, you should use clearTimeout() to clear setTimeout() entries and clearInterval() to clear setInterval() entries. This will help to avoid confusion.

- -

requestAnimationFrame()

- -

requestAnimationFrame() is a specialized looping function created for running animations efficiently in the browser. It is basically the modern version of setInterval() — it executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable frame rate regardless of the environment it is being run in.

- -

It was created in response to perceived problems with setInterval(), which for example doesn't run at a frame rate optimized for the device, sometimes drops frames, continues to run even if the tab is not the active tab or the animation is scrolled off the page, etc. Read more about this on CreativeJS.

- -
-

Note: You can find examples of using requestAnimationFrame() elsewhere in the course — see for example Drawing graphics, and Object building practice.

-
- -

The method takes as an argument a callback to be invoked before the repaint. This is the general pattern you'll see it used in:

- -
function draw() {
-   // Drawing code goes here
-   requestAnimationFrame(draw);
-}
-
-draw();
- -

The idea is that you define a function in which your animation is updated (e.g. your sprites are moved, score is updated, data is refreshed, or whatever), then you call it to start the process off. At the end of the function block you call requestAnimationFrame() with the function reference passed as the parameter, and this instructs the browser to call the function again on the next display repaint. This is then run continuously, as we are calling requestAnimationFrame() recursively.

- -
-

Note: If you want to perform some kind of simple constant DOM animation, CSS Animations are probably faster as they are calculated directly by the browser's internal code rather than JavaScript. If however you are doing something more complex and involving objects that are not directly accessible inside the DOM (such as 2D Canvas API or WebGL objects), requestAnimationFrame() is the better option in most cases.

-
- -

How fast does your animation run?

- -

The smoothness of your animation is directly dependent on your animation's frame rate and it is measured in frames per second (fps). The higher this number is, the smoother your animation will look, to a point.

- -

Since most screens have a refresh rate of 60Hz, the fastest frame rate you can aim for is 60 frames per second (FPS) when working with web browsers. However, more frames means more processing, which can often cause stuttering and skipping — also known as dropping frames, or jank.

- -

If you have a monitor with a 60Hz refresh rate and you want to achieve 60 FPS you have about 16.7 milliseconds (1000 / 60) to execute your animation code to render each frame. This is a reminder that we need to be mindful of the amount of code that we try to run for each pass through the animation loop.

- -

requestAnimationFrame() always tries to get as close to this magic 60 FPS value as possible, although sometimes it isn't possible — if you have a really complex animation and you are running it on a slow computer, your frame rate will be less. requestAnimationFrame() will always do the best it can with what it has available.

- -

How does requestAnimationFrame() differ from setInterval() and setTimeout()?

- -

Let's talk a little bit more about how the requestAnimationFrame() method differs from the other methods we looked at earlier. Looking at our code from above:

- -
function draw() {
-   // Drawing code goes here
-   requestAnimationFrame(draw);
-}
-
-draw();
- -

Let's now see how we'd do the same thing using setInterval():

- -
function draw() {
-   // Drawing code goes here
-}
-
-setInterval(draw, 17);
- -

As we said before, we don't specify a time interval for requestAnimationFrame(); it just runs it as quickly and smoothly as possible in the current conditions. The browser also doesn't waste time running it if the animation is offscreen for some reason, etc.

- -

setInterval() on the other hand requires an interval to be specified. We arrived at our final value of 17 via the formula 1000 milliseconds / 60Hz, and then rounded it up. Rounding up is a good idea, as if you rounded down the browser might try to run the animation faster than 60fps, and it wouldn't make any difference to the smoothness of the animation anyway. As we said before, 60Hz is the standard refresh rate.

- -

Including a timestamp

- -

The actual callback passed to the requestAnimationFrame() function can be given a parameter too — a timestamp value that represents the time since the requestAnimationFrame() started running. This is useful as it allows you to run things at specific times and at a constant pace, regardless of how fast or slow your device might be. The general pattern you'd use looks something like this:

- -
let startTime = null;
-
-function draw(timestamp) {
-    if(!startTime) {
-      startTime = timestamp;
-    }
-
-   currentTime = timestamp - startTime;
-
-   // Do something based on current time
-
-   requestAnimationFrame(draw);
-}
-
-draw();
- -

Browser support

- -

requestAnimationFrame() is supported in slightly more recent browsers than setInterval()/setTimeout() — most interestingly it is available in Internet Explorer 10 and above. So unless you need to support older versions of IE with your code, there is little reason to not use requestAnimationFrame().

- -

A simple example

- -

Enough with the theory; let's go through and build our own requestAnimationFrame() example. We're going to create a simple "spinner animation", the kind you might see displayed in an app when it is busy connecting to the server, etc.

- -
-

Note: In a real world example, you should probably use CSS animations to run this kind of simple animation. However, this kind of example is very useful to demonstrate requestAnimationFrame() usage, and you'd be more like to use this kind of technique when doing something more complex such as updating the display of a game on each frame.

-
- -
    -
  1. -

    First of all, grab a basic HTML template such as this one.

    -
  2. -
  3. -

    Put an empty {{htmlelement("div")}} element inside the {{htmlelement("body")}}, then add a ↻ character inside it. This is a circular arrow character that will act as our spinner for this simple example.

    -
  4. -
  5. -

    Apply the following CSS to the HTML template in whatever way you prefer. This sets a red background on the page, sets the <body> height to 100% of the {{htmlelement("html")}} height, and centers the <div> inside the <body>, horizontally and vertically.

    - -
    html {
    -  background-color: white;
    -  height: 100%;
    -}
    -
    -body {
    -  height: inherit;
    -  background-color: red;
    -  margin: 0;
    -  display: flex;
    -  justify-content: center;
    -  align-items: center;
    -}
    -
    -div {
    -  display: inline-block;
    -  font-size: 10rem;
    -}
    -
  6. -
  7. -

    Insert a {{htmlelement("script")}} element just above the </body> tag.

    -
  8. -
  9. -

    Insert the following JavaScript inside your <script> element. Here we're storing a reference to the <div> inside a constant, setting a rotateCount variable to 0, setting an uninitialized variable that will later be used to contain a reference to the requestAnimationFrame() call, and setting a startTime variable to null, which will later be used to store the start time of the requestAnimationFrame().

    - -
    const spinner = document.querySelector('div');
    -let rotateCount = 0;
    -let startTime = null;
    -let rAF;
    -
    -
  10. -
  11. -

    Below the previous code, insert a draw() function that will be used to contain our animation code, which includes the timestamp parameter:

    - -
    function draw(timestamp) {
    -
    -}
    -
  12. -
  13. -

    Inside draw(), add the following lines. Here we define the start time if it is not defined already (this will only happen on the first loop iteration), and set the rotateCount to a value to rotate the spinner by (the current timestamp, take the starting timestamp, divided by three so it doesn't go too fast):

    - -
      if (!startTime) {
    -   startTime = timestamp;
    -  }
    -
    -  rotateCount = (timestamp - startTime) / 3;
    -
    -
  14. -
  15. -

    Below the previous line inside draw(), add the following block — this checks to see if the value of rotateCount is above 359 (e.g. 360, a full circle). If so, it sets the value to its modulo of 360 (i.e. the remainder left over when the value is divided by 360) so the circle animation can continue uninterrupted, at a sensible, low value. Note that this isn't strictly necessary, but it is easier to work with values of 0-359 degrees than values like "128000 degrees".

    - -
    if (rotateCount > 359) {
    -  rotateCount %= 360;
    -}
    -
  16. -
  17. Next, below the previous block add the following line to actually rotate the spinner: -
    spinner.style.transform = 'rotate(' + rotateCount + 'deg)';
    -
  18. -
  19. -

    At the very bottom inside the draw() function, insert the following line. This is the key to the whole operation — we are setting the variable we defined earlier to an active requestAnimation() call that takes the draw() function as its parameter. This starts the animation off, constantly running the draw() function at a rate of as close to 60 FPS as possible.

    - -
    rAF = requestAnimationFrame(draw);
    -
  20. -
- -
-

Note: You can find this example live on GitHub (see the source code also).

-
- -

Clearing a requestAnimationFrame() call

- -

Clearing a requestAnimationFrame() call can be done by calling the corresponding cancelAnimationFrame() method (note, "cancel" not "clear" as with the "set..." methods), passing it the value returned by the requestAnimationFrame() call to cancel, which we stored in a variable called rAF:

- -
cancelAnimationFrame(rAF);
- -

Active learning: Starting and stopping our spinner

- -

In this exercise, we'd like you to test out the cancelAnimationFrame() method by taking our previous example and updating it, adding an event listener to start and stop the spinner when the mouse is clicked anywhere on the page.

- -

Some hints:

- - - -
-

Note: Try this yourself first; if you get really stuck, check out of our live example and source code.

-
- -

Throttling a requestAnimationFrame() animation

- -

One limitation of requestAnimationFrame() is that you can't choose your frame rate. This isn't a problem most of the time, as generally you want your animation to run as smoothly as possible, but what about when you want to create an old school, 8-bit-style animation?

- -

This was a problem for example in the Monkey Island-inspired walking animation from our Drawing Graphics article:

- -

{{EmbedGHLiveSample("learning-area/javascript/apis/drawing-graphics/loops_animation/7_canvas_walking_animation.html", '100%', 260)}}

- -

In this example we have to animate both the position of the character on the screen, and the sprite being shown. There are only 6 frames in the sprite's animation; if we showed a different sprite frame for every frame displayed on the screen by requestAnimationFrame(), Guybrush would move his limbs too fast and the animation would look ridiculous. We therefore throttled the rate at which the sprite cycles its frames using the following code:

- -
if (posX % 13 === 0) {
-  if (sprite === 5) {
-    sprite = 0;
-  } else {
-    sprite++;
-  }
-}
- -

So we are only cycling a sprite once every 13 animation frames. OK, so it's actually about every 6.5 frames, as we update posX (character's position on the screen) by two each frame:

- -
if(posX > width/2) {
-  newStartPos = -((width/2) + 102);
-  posX = Math.ceil(newStartPos / 13) * 13;
-  console.log(posX);
-} else {
-  posX += 2;
-}
- -

This is the code that works out how to update the position in each animation frame.

- -

The method you use to throttle your animation will depend on your particular code. For example, in our spinner example we could make it appear to move slower by only increasing our rotateCount by one on each frame instead of two.

- -

Active learning: a reaction game

- -

For our final section of this article, we'll create a 2-player reaction game. Here we have two players, one of whom controls the game using the A key, and the other with the L key.

- -

When the Start button is pressed, a spinner like the one we saw earlier is displayed for a random amount of time between 5 and 10 seconds. After that time, a message will appear saying "PLAYERS GO!!" — once this happens, the first player to press their control button will win the game.

- -

{{EmbedGHLiveSample("learning-area/javascript/asynchronous/loops-and-intervals/reaction-game.html", '100%', 500)}}

- -

Let's work through this.

- -
    -
  1. -

    First of all, download the starter file for the app — this contains the finished HTML structure and CSS styling, giving us a game board that shows the two players' information (as seen above), but with the spinner and results paragraph displayed on top of one another. We just have to write the JavaScript code.

    -
  2. -
  3. -

    Inside the empty {{htmlelement("script")}} element on your page, start by adding the following lines of code that define some constants and variables we'll need in the rest of the code:

    - -
    const spinner = document.querySelector('.spinner p');
    -const spinnerContainer = document.querySelector('.spinner');
    -let rotateCount = 0;
    -let startTime = null;
    -let rAF;
    -const btn = document.querySelector('button');
    -const result = document.querySelector('.result');
    - -

    In order, these are:

    - -
      -
    1. A reference to our spinner, so we can animate it.
    2. -
    3. A reference to the {{htmlelement("div")}} element that contains the spinner, used for showing and hiding it.
    4. -
    5. A rotate count — how much we want to show the spinner rotated on each frame of the animation.
    6. -
    7. A null start time — will be populated with a start time when the spinner starts spinning.
    8. -
    9. An uninitialized variable to later store the {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} call that animates the spinner.
    10. -
    11. A reference to the Start button.
    12. -
    13. A reference to the results paragraph.
    14. -
    -
  4. -
  5. -

    Next, below the previous lines of code, add the following function. This simply takes two numerical inputs and returns a random number between the two. We'll need this to generate a random timeout interval later on.

    - -
    function random(min,max) {
    -  var num = Math.floor(Math.random()*(max-min)) + min;
    -  return num;
    -}
    -
  6. -
  7. -

    Next add in the draw() function, which animates the spinner. This is exactly the same as the version seen in the simple spinner example we looked at earlier:

    - -
      function draw(timestamp) {
    -    if(!startTime) {
    -     startTime = timestamp;
    -    }
    -
    -    let rotateCount = (timestamp - startTime) / 3;
    -    spinner.style.transform = 'rotate(' + rotateCount + 'deg)';
    -
    -    if(rotateCount > 359) {
    -      rotateCount -= 360;
    -    }
    -
    -    rAF = requestAnimationFrame(draw);
    -  }
    -
  8. -
  9. -

    Now it is time to set up the initial state of the app when the page first loads. Add the following two lines, which simply hide the results paragraph and spinner container using display: none;.

    - -
    result.style.display = 'none';
    -spinnerContainer.style.display = 'none';
    -
  10. -
  11. -

    We'll also define a reset() function, which sets the app back to the original state required to start the game again after it has been played. Add the following at the bottom of your code:

    - -
    function reset() {
    -  btn.style.display = 'block';
    -  result.textContent = '';
    -  result.style.display = 'none';
    -}
    -
  12. -
  13. -

    OK, enough preparation.  Let's make the game playable! Add the following block to your code. The start() function calls draw() to start the spinner spinning and display it in the UI, hides the Start button so we can't mess up the game by starting it multiple times concurrently, and runs a setTimeout() call that runs a setEndgame() function after a random interval between 5 and 10 seconds has passed. We also add an event listener to our button to run the start() function when it is clicked.

    - -
    btn.addEventListener('click', start);
    -
    -function start() {
    -  draw();
    -  spinnerContainer.style.display = 'block';
    -  btn.style.display = 'none';
    -  setTimeout(setEndgame, random(5000,10000));
    -}
    - -
    -

    Note: You'll see that in this example we are calling setTimeout() without storing the return value (so not let myTimeout = setTimeout(functionName, interval)). This works and is fine, as long as you don't need to clear your interval/timeout at any point. If you do, you'll need to save the returned identifier.

    -
    - -

    The net result of the previous code is that when the Start button is pressed, the spinner is shown and the players are made to wait a random amount of time before they are then asked to press their button. This last part is handled by the setEndgame() function, which we should define next.

    -
  14. -
  15. -

    So add the following function to your code next:

    - -
    function setEndgame() {
    -  cancelAnimationFrame(rAF);
    -  spinnerContainer.style.display = 'none';
    -  result.style.display = 'block';
    -  result.textContent = 'PLAYERS GO!!';
    -
    -  document.addEventListener('keydown', keyHandler);
    -
    -  function keyHandler(e) {
    -    console.log(e.key);
    -    if(e.key === 'a') {
    -      result.textContent = 'Player 1 won!!';
    -    } else if(e.key === 'l') {
    -      result.textContent = 'Player 2 won!!';
    -    }
    -
    -    document.removeEventListener('keydown', keyHandler);
    -    setTimeout(reset, 5000);
    -  };
    -}
    - -

    Stepping through this:

    - -
      -
    1. First we cancel the spinner animation with {{domxref("window.cancelAnimationFrame", "cancelAnimationFrame()")}} (it is always good to clean up unneeded processes), and hide the spinner container.
    2. -
    3. Next we display the results paragraph and set its text content to "PLAYERS GO!!" to signal to the players that they can now press their button to win.
    4. -
    5. We then attach a keydown event listener to our document — when any button is pressed down, the keyHandler() function is run.
    6. -
    7. Inside keyHandler(), we include the event object as a parameter (represented by e) — its {{domxref("KeyboardEvent.key", "key")}} property contains the key that was just pressed, and we can use this to respond to specific key presses with specific actions.
    8. -
    9. We first log e.key to the console, which is a useful way of finding out the key value of different keys you are pressing.
    10. -
    11. When e.key is "a", we display a message to say that Player 1 won, and when e.key is "l", we display a message to say Player 2 won. Note that this will only work with lowercase a and l — if an uppercase A or L is submitted (the key plus Shift), it is counted as a different key.
    12. -
    13. Regardless of which one of the player control keys was pressed, we remove the keydown event listener using {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} so that once the winning press has happened, no more keyboard input is possible to mess up the final game result. We also use setTimeout() to call reset() after 5 seconds — as we explained earlier, this function resets the game back to its original state so that a new game can be started.
    14. -
    -
  16. -
- -

That's it, you're all done.

- -
-

Note: If you get stuck, check out our version of the reaction game (see the source code also).

-
- -

Conclusion

- -

So that's it — all the essentials of async loops and intervals covered in one article. You'll find these methods useful in a lot of situations, but take care not to overuse them — since these still run on the main thread, heavy and intensive callbacks (especially those that manipulate the DOM) can really slow down a page if you're not careful.

- -

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}

- - -

במודול זה

- - -- cgit v1.2.3-54-g00ecf