Отладка javascript в google chrome
Давайте отвлечёмся от написания кода и поговорим о его отладке.
Отладка – это процесс поиска и исправления ошибок в скрипте. Все современные браузеры и большинство других сред разработки поддерживают инструменты для отладки – специальный графический интерфейс, который сильно упрощает отладку. Он также позволяет по шагам отследить, что именно происходит в нашем коде.
Мы будем использовать браузер Chrome, так как у него достаточно возможностей, в большинстве других браузеров процесс будет схожим.
Google Chrome
В её JavaScript-коде закралась ошибка. Она не видна обычному посетителю, поэтому давайте найдём её при помощи инструментов разработки.
Нажмите F12 или, если вы используете Mac, Cmd + Opt + J .
По умолчанию в инструментах разработчика откроется вкладка Console (консоль).
Она выглядит приблизительно следующим образом:
Точный внешний вид инструментов разработки зависит от используемой версии Chrome. Время от времени некоторые детали изменяются, но в целом внешний вид остаётся примерно похожим на предыдущие версии.
Обычно при нажатии Enter введённая строка кода сразу выполняется.
Чтобы перенести строку, нажмите Shift + Enter . Так можно вводить более длинный JS-код.
Теперь мы явно видим ошибки, для начала этого вполне достаточно. Мы ещё вернёмся к инструментам разработчика позже и более подробно рассмотрим отладку кода в главе Отладка в браузере.
Firefox, Edge и другие
Инструменты разработчика в большинстве браузеров открываются при нажатии на F12 .
Их внешний вид и принципы работы мало чем отличаются. Разобравшись с инструментами в одном браузере, вы без труда сможете работать с ними и в другом.
Команда debugger
Выполнение кода можно также приостановить с помощью команды debugger прямо изнутри самого кода:
Такая команда сработает только если открыты инструменты разработки, иначе браузер ее проигнорирует.
Safari
Safari (браузер для Mac, не поддерживается в системах Windows/Linux) всё же имеет небольшое отличие. Для начала работы нам нужно включить «Меню разработки» («Developer menu»).
Откройте Настройки (Preferences) и перейдите к панели «Продвинутые» (Advanced). В самом низу вы найдёте чекбокс:
Теперь консоль можно активировать нажатием клавиш Cmd + Opt + C . Также обратите внимание на новый элемент меню «Разработка» («Develop»). В нем содержится большое количество команд и настроек.
Консоль
При нажатии на клавишу Esc в нижней части экрана вызывается консоль, где можно вводить команды и выполнять их клавишей Enter .
Результат выполнения инструкций сразу же отображается в консоли.
Например, результатом 1+2 будет 3 , а вызов функции hello("debugger") ничего не возвращает, так что результатом будет undefined :
Остановимся и оглядимся
В нашем примере функция hello() вызывается во время загрузки страницы, поэтому для начала отладки (после того, как мы поставили точки останова) проще всего её перезагрузить. Нажмите F5 (Windows, Linux) или Cmd + R (Mac).
Выполнение прервётся на четвёртой строчке (где находится точка останова):
Чтобы понять, что происходит в коде, щёлкните по стрелочкам справа:
Watch – показывает текущие значения для любых выражений.
Вы можете нажать на + и ввести выражение. Отладчик покажет его значение, автоматически пересчитывая его в процессе выполнения.
Call Stack – показывает цепочку вложенных вызовов.
В текущий момент отладчик находится внутри вызова hello() , вызываемого скриптом в index.html (там нет функции, поэтому она называется “анонимной”).
Если вы нажмёте на элемент стека (например, «anonymous»), отладчик перейдёт к соответствующему коду, и нам представляется возможность его проанализировать.
Scope показывает текущие переменные.
Local показывает локальные переменные функций, а их значения подсвечены прямо в исходном коде.
В Global перечисляются глобальные переменные (то есть вне каких-либо функций).
Там также есть ключевое слово this , которое мы ещё не изучали, но скоро изучим.
Точки останова (breakpoints)
Давайте разберёмся, как работает код нашей тестовой страницы. В файле hello.js щёлкните на номере строки 4 . Да-да, щёлкайте именно по самой цифре, не по коду.
Ура! Вы поставили точку останова. А теперь щёлкните по цифре 8 на восьмой линии.
Вот что в итоге должно получиться (синим это те места, по которым вы должны щёлкнуть):
Точка останова – это участок кода, где отладчик автоматически приостановит исполнение JavaScript.
Пока исполнение поставлено «на паузу», мы можем просмотреть текущие значения переменных, выполнить команды в консоли, другими словами, выполнить отладку кода.
В правой части графического интерфейса мы видим список точек останова. А когда таких точек выставлено много, да ещё и в разных файлах, этот список поможет эффективно ими управлять:
- Быстро перейдите к точке останова в коде (нажав на неё на правой панели).
- Временно отключите точку останова, сняв с неё галочку.
- Удалите точку останова, щёлкнув правой кнопкой мыши и выбрав Remove (Удалить).
- …и так далее.
Щелчок правой кнопкой мыши по номеру строки позволяет создать условную точку останова. Она сработает только в тот момент, когда выражение, которое вы должны указать при создании такой точки, истинно.
Это удобно, когда нам нужно остановиться только для при определённом значении переменной или для определённых параметров функции.
Итого
- Инструменты разработчика позволяют нам смотреть ошибки, выполнять команды, проверять значение переменных и ещё много всего полезного.
- В большинстве браузеров, работающих под Windows, инструменты разработчика можно открыть, нажав F12 . В Chrome для Mac используйте комбинацию Cmd + Opt + J , Safari: Cmd + Opt + C (необходимо предварительное включение «Меню разработчика»).
Теперь наше окружение полностью настроено. В следующем разделе мы перейдём непосредственно к JavaScript.
This tutorial teaches you the basic workflow for debugging any JavaScript issue in DevTools. Read on, or watch the video version of this tutorial, below.
Finding a series of actions that consistently reproduces a bug is always the first step to debugging.
Click Open Demo. The demo opens in a new tab.
Enter 5 in the Number 1 text box.
Enter 1 in the Number 2 text box.
Click Add Number 1 and Number 2. The label below the button says 5 + 1 = 51 . The result should be 6 . This is the bug you're going to fix.
Figure 1. The result of 5 + 1 is 51. It should be 6.
DevTools provides a lot of different tools for different tasks, such as changing CSS, profiling page load performance, and monitoring network requests. The Sources panel is where you debug JavaScript.
Open DevTools by pressing Command+Option+I (Mac) or Control+Shift+I (Windows, Linux). This shortcut opens the Console panel.
Figure 2. The Console panel
Click the Sources tab.
Figure 3. The Sources panel
The Sources panel UI has 3 parts:
Figure 4. The 3 parts of the Sources panel UI
- The File Navigator pane. Every file that the page requests is listed here.
- The Code Editor pane. After selecting a file in the File Navigator pane, the contents of that file are displayed here.
- The JavaScript Debugging pane. Various tools for inspecting the page's JavaScript. If your DevTools window is wide, this pane is displayed to the right of the Code Editor pane.
A common method for debugging a problem like this is to insert a lot of console.log() statements into the code, in order to inspect values as the script executes. For example:
The console.log() method may get the job done, but breakpoints can get it done faster. A breakpoint lets you pause your code in the middle of its execution, and examine all values at that moment in time. Breakpoints have a few advantages over the console.log() method:
- With console.log() , you need to manually open the source code, find the relevant code, insert the console.log() statements, and then reload the page in order to see the messages in the Console. With breakpoints, you can pause on the relevant code without even knowing how the code is structured.
- In your console.log() statements you need to explicitly specify each value that you want to inspect. With breakpoints, DevTools shows you the values of all variables at that moment in time. Sometimes there are variables affecting your code that you're not even aware of.
In short, breakpoints can help you find and fix bugs faster than the console.log() method.
If you take a step back and think about how the app works, you can make an educated guess that the incorrect sum ( 5 + 1 = 51 ) gets computed in the click event listener that's associated to the Add Number 1 and Number 2 button. Therefore, you probably want to pause the code around the time that the click listener executes. Event Listener Breakpoints let you do exactly that:
In the JavaScript Debugging pane, click Event Listener Breakpoints to expand the section. DevTools reveals a list of expandable event categories, such as Animation and Clipboard.
Next to the Mouse event category, click Expand . DevTools reveals a list of mouse events, such as click and mousedown. Each event has a checkbox next to it.
Check the click checkbox. DevTools is now set up to automatically pause when any click event listener executes.
Figure 5. The click checkbox is enabled
Back on the demo, click Add Number 1 and Number 2 again. DevTools pauses the demo and highlights a line of code in the Sources panel. DevTools should be paused on this line of code:
If you're paused on a different line of code, press Resume Script Execution until you're paused on the correct line.
Note: If you paused on a different line, you have a browser extension that registers a click event listener on every page that you visit. You were paused in the extension's click listener. If you use Incognito Mode to browse in private, which disables all extensions, you can see that you pause on the correct line of code every time.
Event Listener Breakpoints are just one of many types of breakpoints available in DevTools. It's worth memorizing all the different types, because each type ultimately helps you debug different scenarios as quickly as possible. See Pause Your Code With Breakpoints to learn when and how to use each type.
One common cause of bugs is when a script executes in the wrong order. Stepping through your code enables you to walk through your code's execution, one line at a time, and figure out exactly where it's executing in a different order than you expected. Try it now:
On the Sources panel of DevTools, click Step into next function call to step through the execution of the onClick() function, one line at a time. DevTools highlights the following line of code:
Click Step over next function call . DevTools executes inputsAreEmpty() without stepping into it. Notice how DevTools skips a few lines of code. This is because inputsAreEmpty() evaluated to false, so the if statement's block of code didn't execute.
That's the basic idea of stepping through code. If you look at the code in get-started.js , you can see that the bug is probably somewhere in the updateLabel() function. Rather than stepping through every line of code, you can use another type of breakpoint to pause the code closer to the probable location of the bug.
Line-of-code breakpoints are the most common type of breakpoint. When you've got a specific line of code that you want to pause on, use a line-of-code breakpoint:
Look at the last line of code in updateLabel() :
To the left of the code you can see the line number of this particular line of code, which is 32. Click on 32. DevTools puts a blue icon on top of 32. This means that there is a line-of-code breakpoint on this line. DevTools now always pauses before this line of code is executed.
Click Resume script execution . The script continues executing until it reaches line 32. On lines 29, 30, and 31, DevTools prints out the values of addend1 , addend2 , and sum to the right of each line's semi-colon.
Figure 6. DevTools pauses on the line-of-code breakpoint on line 32
The values of addend1 , addend2 , and sum look suspicious. They're wrapped in quotes, which means that they're strings. This is a good hypothesis for the explaining the cause of the bug. Now it's time to gather more information. DevTools provides a lot of tools for examining variable values.
When you're paused on a line of code, the Scope pane shows you what local and global variables are currently defined, along with the value of each variable. It also shows closure variables, when applicable. Double-click a variable value to edit it. When you're not paused on a line of code, the Scope pane is empty.
Figure 7. The Scope pane
The Watch Expressions tab lets you monitor the values of variables over time. As the name implies, Watch Expressions aren't just limited to variables. You can store any valid JavaScript expression in a Watch Expression. Try it now:
Click the Watch tab.
Click Add Expression .
Type typeof sum .
Press Enter. DevTools shows typeof sum: "string" . The value to the right of the colon is the result of your Watch Expression.
Figure 8. The Watch Expression pane (bottom-right), after creating the typeof sum Watch Expression. If your DevTools window is large, the Watch Expression pane is on the right, above the Event Listener Breakpoints pane.
As suspected, sum is being evaluated as a string, when it should be a number. You've now confirmed that this is the cause of the bug.
In addition to viewing console.log() messages, you can also use the Console to evaluate arbitrary JavaScript statements. In terms of debugging, you can use the Console to test out potential fixes for bugs. Try it now:
If you don't have the Console drawer open, press Escape to open it. It opens at the bottom of your DevTools window.
In the Console, type parseInt(addend1) + parseInt(addend2) . This statement works because you are paused on a line of code where addend1 and addend2 are in scope.
Press Enter. DevTools evaluates the statement and prints out 6 , which is the result you expect the demo to produce.
Figure 9. The Console drawer, after evaluating parseInt(addend1) + parseInt(addend2) .
You've found a fix for the bug. All that's left is to try out your fix by editing the code and re-running the demo. You don't need to leave DevTools to apply the fix. You can edit JavaScript code directly within the DevTools UI. Try it now:
- Click Resume script execution.
- In the Code Editor, replace line 31, var sum = addend1 + addend2 , with var sum = parseInt(addend1) + parseInt(addend2) .
- Press Command+S (Mac) or Control+S (Windows, Linux) to save your change.
- Click Deactivate breakpoints. It changes blue to indicate that it's active. While this is set, DevTools ignores any breakpoints you've set.
- Try out the demo with different values. The demo now calculates correctly.
Caution: This workflow only applies a fix to the code that is running in your browser. It won't fix the code for all users that visit your page. To do that, you need to fix the code that's on your servers.
Congratulations! You now know how to make the most of Chrome DevTools when debugging JavaScript. The tools and methods you learned in this tutorial can save you countless hours.
This tutorial only showed you two ways to set breakpoints. DevTools offers many other ways, including:
- Conditional breakpoints that are only triggered when the condition that you provide is true.
- Breakpoints on caught or uncaught exceptions.
- XHR breakpoints that are triggered when the requested URL matches a substring that you provide.
See Pause Your Code With Breakpoints to learn when and how to use each type.
There's a couple of code stepping controls that weren't explained in this tutorial. See Step over line of code to learn more.
Discover new debugging workflows with this comprehensive reference of Chrome DevTools debugging features.
Set a breakpoint so that you can pause your code in the middle of its execution.
See Pause Your Code With Breakpoints to learn how to set breakpoints.
While the execution is paused, hover over a class or function name to preview its properties.
Once your code is paused, step through it, one line at a time, investigating control flow and property values along the way.
When paused on a line of code containing a function that's not relevant to the problem you're debugging, click Step over to execute the function without stepping into it.
Figure 1. Step over, outlined in blue
For example, suppose you're debugging the following code:
You're paused on A . By pressing Step over, DevTools executes all the code in the function that you're stepping over, which is B and C . DevTools then pauses on D .
When paused on a line of code containing a function call that is related to the problem you're debugging, click Step into to investigate that function further.
Figure 2. Step into, outlined in blue
For example, suppose you're debugging the following code:
You're paused on A . By pressing Step into, DevTools executes this line of code, then pauses on B .
When paused inside of a function that is not related to the problem you're debugging, click Step out to execute the rest of the function's code.
Figure 3. Step out, outlined in blue
For example, suppose you're debugging the following code:
You're paused on A . By pressing Step out, DevTools executes the rest of the code in getName() , which is just B in this example, and then pauses on C .
When debugging a long function, there may be a lot of code that is not related to the problem you're debugging.
You could step through all the lines, but that can be tedious. You could set a line-of-code breakpoint on the line you're interested in and then press Resume Script Execution , but there's a faster way.
Right-click the line of code that you're interested in, and select Continue to here. DevTools runs all of the code up to that point, and then pauses on that line.
Figure 4. Selecting Continue to here
To continue your script's execution after a pause, click Resume Script Execution . DevTools executes the script up until the next breakpoint, if any.
Figure 6. Resume script execution, outlined in blue
To ignore all breakpoints and force your script to resume execution, click and hold Resume Script Execution and then select Force script execution .
Figure 7. Selecting Force script execution
When working with web workers or service workers, click on a context listed in the Threads pane to switch to that context. The blue arrow icon represents which context is currently selected.
Figure 8. The Threads pane, outlined in blue
For example, suppose that you're paused on a breakpoint in both your main script and your service worker script. You want to view the local and global properties for the service worker context, but the Sources panel is showing the main script context. By clicking on the service worker entry in the Threads pane, you'd be able to switch to that context.
While paused on a line of code, use the Scope pane to view and edit the values of properties and variables in the local, closure, and global scopes.
- Double-click a property value to change it.
- Non-enumerable properties are greyed out.
Figure 9. The Scope pane, outlined in blue
While paused on a line of code, use the Call Stack pane to view the call stack that got you to this point.
If you're working with async code, check the Async checkbox to enable async call stacks.
Click on an entry to jump to the line of code where that function was called. The blue arrow icon represents which function DevTools is currently highlighting.
Figure 10. The Call Stack pane, outlined in blue
Note: When not paused on a line of code, the Call Stack pane is empty.
Right-click anywhere in the Call Stack pane and select Copy stack trace to copy the current call stack to the clipboard.
Figure 11. Selecting Copy Stack Trace
Below is an example of the output:
Ignore a script to skip it while debugging. When ignored, a script is obscured in the Call Stack pane, and you never step into the script's functions when you step through your code.
For example, suppose you're stepping through this code:
A is a third-party library that you trust. If you're confident that the problem you're debugging is not related to the third-party library, then it makes sense to ignore the script.
To ignore a script from the Editor pane:
Figure 12. Ignoring a script from the Editor pane
To ignore a script from the Call Stack pane:
Figure 13. Ignoring a script from the Call Stack pane
To ignore a single script or pattern of scripts from Settings:
Figure 14. Ignoring a script from Settings
If you find yourself running the same debug code in the Console over and over, consider Snippets. Snippets are executable scripts that you author, store, and run within DevTools.
Use the Watch pane to watch the values of custom expressions. You can watch any valid JavaScript expression.
Figure 15. The Watch pane, outlined in blue
Click Format to make a minified file human-readable.
Figure 16. Format, outlined in blue
When fixing a bug, you often want to test out some changes to your JavaScript code. You don't need to make the changes in an external browser and then reload the page. You can edit your script in DevTools.
To edit a script:
Open the file in the Editor pane of the Sources panel.
Make your changes in the Editor pane.
Press Command + S (Mac) or Ctrl + S (Windows, Linux) to save. DevTools patches the entire JS file into Chrome's JavaScript engine.
This interactive tutorial shows you how to run JavaScript in the Chrome DevTools Console. See Get Started With Logging Messages to learn how to log messages to the Console. See Get Started With Debugging JavaScript to learn how to pause JavaScript code and step through it one line at a time.
Figure 1. The Console.
The Console is a REPL, which stands for Read, Evaluate, Print, and Loop. It reads the JavaScript that you type into it, evaluates your code, prints out the result of your expression, and then loops back to the first step.
This tutorial is designed so that you can open up the demo and try all the workflows yourself. When you physically follow along, you're more likely to remember the workflows later.
Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, ChromeOS) to open the Console, right here on this very page.
Figure 2. This tutorial on the left, and DevTools on the right.
When building or debugging a page, it's often useful to run statements in the Console in order to change how the page looks or runs.
Notice the text in the button below.
Type document.getElementById('hello').textContent = 'Hello, Console!' in the Console and then press Enter to evaluate the expression. Notice how the text inside the button changes.
Figure 3. How the Console looks after evaluating the expression above.
Below the code that you evaluated you see "Hello, Console!" . Recall the 4 steps of REPL: read, evaluate, print, loop. After evaluating your code, a REPL prints the result of the expression. So "Hello, Console!" must be the result of evaluating document.getElementById('hello').textContent = 'Hello, Console!' .
Sometimes, you just want a code playground where you can test some code, or try out new JavaScript features you're not familiar with. The Console is a perfect place for these kinds of experiments.
Type 5 + 15 in the Console. The result 20 will appear below your expression (unless your expression takes too much time to evaluate).
Press Enter to evaluate the expression. The Console prints the result of the expression below your code. Figure 4 below shows how your Console should look after evaluating this expression.
Type the following code into the Console. Try typing it out, character-by-character, rather than copy-pasting it.
See define default values for function arguments if you're unfamiliar with the b=20 syntax.
Now, call the function that you just defined.
Figure 4. How the Console looks after evaluating the expressions above.
add(25) evaluates to 45 because when the add function is called without a second argument, b defaults to 20 .
You will not be able to run any code in this console session until your function has returned. If that takes too long, you can use the Task Manager to cancel the time-intensive computation; however, it will also cause the current page to fail and all data you have entered will be lost.
See Run JavaScript to explore more features related to running JavaScript in the Console.
DevTools lets you pause a script in the middle of its execution. While you're paused, you can use the Console to view and change the page's window or DOM at that moment in time. This makes for a powerful debugging workflow. See Get Started With Debugging JavaScript for an interactive tutorial.
The Console also supports a set of format specifiers. See Format and style messages in the Console to explore all the method to format and style console messages.
Apart from that, the Console also has a set of convenience functions that make it easier to interact with a page. For example:
- Rather than typing document.querySelector() to select an element, you can type $() . This syntax is inspired by jQuery, but it's not actually jQuery. It's just an alias for document.querySelector() .
- debug(function) effectively sets a breakpoint on the first line of that function.
- keys(object) returns an array containing the keys of the specified object.
See Console Utilities API Reference to explore all the convenience functions.
Логирование
Чтобы вывести что-то на консоль из нашего кода, существует функция console.log .
Код уязвим для ошибок. И вы, скорее всего, будете делать ошибки в коде… Впрочем, давайте будем откровенны: вы точно будете совершать ошибки в коде. В конце концов, вы человек, а не робот.
Но по умолчанию в браузере ошибки не видны. То есть, если что-то пойдёт не так, мы не увидим, что именно сломалось, и не сможем это починить.
Для решения задач такого рода в браузер встроены так называемые «Инструменты разработки» (Developer tools или сокращённо — devtools).
Chrome и Firefox снискали любовь подавляющего большинства программистов во многом благодаря своим отменным инструментам разработчика. Остальные браузеры, хотя и оснащены подобными инструментами, но всё же зачастую находятся в роли догоняющих и по качеству, и по количеству свойств и особенностей. В общем, почти у всех программистов есть свой «любимый» браузер. Другие используются только для отлова и исправления специфичных «браузерозависимых» ошибок.
Для начала знакомства с этими мощными инструментами давайте выясним, как их открывать, смотреть ошибки и запускать команды JavaScript.
Панель «Исходный код» («Sources»)
Версия Chrome, установленная у вас, может выглядеть немного иначе, однако принципиальных отличий не будет.
- Работая в Chrome, откройте тестовую страницу.
- Включите инструменты разработчика, нажав F12 (Mac: Cmd + Opt + I ).
- Щёлкните по панели Sources («исходный код»).
При первом запуске получаем следующее:
Кнопка-переключатель откроет вкладку со списком файлов.
Кликните на неё и выберите hello.js в дереве файлов. Вот что появится:
Интерфейс состоит из трёх зон:
- В зоне File Navigator (панель для навигации файлов) показаны файлы HTML, JavaScript, CSS, включая изображения, используемые на странице. Здесь также могут быть файлы различных расширений Chrome.
- Зона Code Editor (редактор кода) показывает исходный код.
- Наконец, зона JavaScript Debugging (панель отладки JavaScript) отведена для отладки, скоро мы к ней вернёмся.
Чтобы скрыть список ресурсов и освободить экранное место для исходного кода, щёлкните по тому же переключателю .
Пошаговое выполнение скрипта
А теперь давайте пошагаем по нашему скрипту.
Для этого есть кнопки в верхней части правой панели. Давайте рассмотрим их.
– «Resume»: продолжить выполнение, быстрая клавиша F8 .
Возобновляет выполнение кода. Если больше нет точек останова, то выполнение просто продолжается, без контроля отладчиком.
Вот, что мы увидим, кликнув на неё:
Выполнение кода возобновилось, дошло до другой точки останова внутри say() , и отладчик снова приостановил выполнение. Обратите внимание на пункт «Call stack» справа: в списке появился ещё один вызов. Сейчас мы внутри say() .
– «Step»: выполнить следующую команду, быстрая клавиша F9 .
Выполняет следующую инструкцию. Если мы нажмём на неё сейчас, появится alert .
Нажатие на эту кнопку снова и снова приведёт к пошаговому выполнению всех инструкций скрипта одного за другим.
– «Step over»: выполнить следующую команду, но не заходя внутрь функции, быстрая клавиша F10 .
Работает аналогично предыдущей команде «Step», но ведёт себя по-другому, если следующая инструкция является вызовом функции (имеется ввиду: не встроенная, как alert , а объявленная нами функция).
Если сравнить, то команда «Step» переходит во вложенный вызов функцию и приостанавливает выполнение в первой строке, в то время как «Step over» выполняет вызов вложенной функции незаметно для нас, пропуская её внутренний код.
Затем выполнение приостанавливается сразу после вызова функции.
Это хорошо, если нам не интересно видеть, что происходит внутри вызова функции.
– «Step into», быстрая клавиша F11 .
Это похоже на «Step», но ведёт себя по-другому в случае асинхронных вызовов функций. Если вы только начинаете изучать JavaScript, то можете не обращать внимания на разницу, так как у нас ещё нет асинхронных вызовов.
На будущее просто помните, что команда «Step» игнорирует асинхронные действия, такие как setTimeout (вызов функции по расписанию), которые выполняются позже. «Step into» входит в их код, ожидая их, если это необходимо. См. DevTools manual для получения более подробной информации.
– «Step out»: продолжить выполнение до завершения текущей функции, быстрая клавиша Shift + F11 .
Продолжает выполнение и останавливает его в самой последней строке текущей функции. Это удобно, когда мы случайно вошли во вложенный вызов, используя , но это нас не интересует, и мы хотим продолжить его до конца как можно скорее.
– активировать/деактивировать все точки останова(breakpoints).
Эта кнопка не влияет на выполнение кода, она лишь позволяет массово включить/отключить точки останова.
– включить/отключить автоматическую паузу в случае ошибки.
При включении, если открыты инструменты разработчика, ошибка при выполнении скрипта автоматически приостанавливает его. Затем мы можем проанализировать переменные в отладчике, чтобы понять, что пошло не так. Поэтому, если наш скрипт умирает с ошибкой, мы можем открыть отладчик, включить эту опцию и перезагрузить страницу, чтобы увидеть, где он умирает и каков контекст в этот момент.
Щелчок правой кнопкой мыши по строке кода открывает контекстное меню с отличной опцией под названием «Continue to here» («продолжить до этого места»).
Это удобно, когда мы хотим перейти на несколько шагов вперёд к строке, но лень устанавливать точку останова (breakpoint).
Читайте также: