Here’s a simple JavaScript example that you can run and debug using breakpoints. This code simulates a user interacting with a form, and we’ll set breakpoints to inspect the state of the program during execution. You can use this to step through the code.
Create a new HTML file and paste the following code into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Debugging with Breakpoints</title>
</head>
<body>
<h1>Simple Form</h1>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<button type="submit">Submit</button>
</form>
<script>
// Form submission handler
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page refresh
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
console.log('Form submitted with values:');
console.log('Name:', name);
console.log('Email:', email);
// Simulating an asynchronous operation (e.g., saving to a database)
setTimeout(() => {
console.log('Data saved successfully!');
}, 2000);
});
// Some simple validation
function validateForm() {
const name = document.getElementById('name').value;
if (name.trim() === '') {
alert('Name cannot be empty!');
return false;
}
return true;
}
</script>
</body>
</html>
Ctrl + Shift + I
(Cmd + Option + I
on Mac).Set Breakpoints:
setTimeout()
callback).Interact with the Form: Fill out the form and click Submit. The page won't refresh due to event.preventDefault()
.
Step Through the Code:
name
and email
variables.