<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
for (let i =0 ; true; i++){
alert(i + 'repeat')
const isContinue = confirm('continue?')
if (!isContinue){
break
}
}
alert('exit program')
</script>
</head>
<body>
</body>
</html>
### How the Script Works:
- **Initialization**: `for (let i =0; true; i++)` starts a loop with `i` initialized at `0`. The condition in the middle of the `for` loop declaration is simply `true`, which means the loop will continue indefinitely until explicitly broken out of.
- **Alert Dialog**: Inside the loop, `alert(i + 'repeat')` displays an alert dialog to the user that shows the current value of `i` followed by the text 'repeat'. This provides a running count of how many times the loop has executed.
- **Confirmation Dialog**: `const isContinue = confirm('continue?')` then presents a confirmation dialog with the buttons OK (to continue) and Cancel (to not continue). The user’s choice is stored in the `isContinue` variable.
- If the user clicks OK, `isContinue` becomes `true`, and the loop continues to the next iteration.
- If the user clicks Cancel, `isContinue` becomes `false`. The `if (!isContinue)` condition then evaluates to `true`, and the `break` statement terminates the loop.
- **Exit Alert**: After breaking out of the loop, `alert('exit program')` displays a final message indicating that the program has ended.
### Execution Flow:
1. When the document is loaded in a web browser, the script automatically starts executing.
2. The user is presented with an alert dialog showing "0repeat" (with `0` incrementing in each subsequent iteration) and then immediately after closing the alert, a confirmation dialog asking "continue?".
3. This process repeats, incrementing the number displayed each time, until the user chooses to cancel the continuation.
4. Once canceled, a final alert dialog stating "exit program" is shown, marking the end of the script's execution.
### Purpose and Use:
This script is a simple demonstration of how to interact with users through dialog boxes in a web browser, utilizing user input to control the flow of the program. It effectively uses a loop for repeated actions, offers user interaction to determine the continuation of the loop, and provides feedback based on user decisions. This pattern can be useful in various scenarios where user confirmation is needed before proceeding with further actions in a web application.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 4) while (0) | 2024.12.01 |
---|---|
chapter 4) continue (0) | 2024.11.30 |
chapter 3) Using nested conditionals (0) | 2024.11.28 |
chapter 3) Using conditional operators (0) | 2024.11.27 |
chapter 3) Using switch conditional statements (0) | 2024.11.26 |