Pair programming with ChatGPT

Pair programming with ChatGPT

It's not like there's anyone left who needs to be convinced that generative AI is going to impact everyone, everywhere or that it's the most game-changing development since the smartphone. But that doesn't negate the astonishment we're all experiencing when an engine like ChatGPT knocks us off our collective chairs with the breathtakingly efficient delivery of a task that would have taken hours to accomplish.

I had such a moment recently with a rather simple web development job. While experimenting with OpenAI's APIs, I noticed that latency with the calls can be significant. To combat this, I wanted to display a loading message covering the user's screen while the application made the call to the service. This is a perfectly simple web development task that wouldn't take most experienced coders much time. But it's also one of those chores that few folks want to spend any time on, no matter how minimal.

So I turned to ChatGPT to see if AI could save the day (or at least an hour or so). Here was my first prompt:

Write some javascript that triggers when a link is clicked on a webpage that overlays the entire screen with a "waiting" icon or message, so that the user knows the next page is still loading.

The initial output got me 90% of the way there:

// get a reference to all the links on the pag
const links = document.querySelectorAll('a');

// add a click event listener to each link
links.forEach(link => {
? link.addEventListener('click', event => {
? ? // prevent the default link behavior
? ? event.preventDefault();

? ? // create a div element to display the "waiting" message
? ? const waitingDiv = document.createElement('div');
? ? waitingDiv.innerHTML = 'Please wait...';

? ? // add styles to the waiting div to position it over the entire screen
? ? waitingDiv.style.position = 'fixed';
? ? waitingDiv.style.top = 0;
? ? waitingDiv.style.left = 0;
? ? waitingDiv.style.width = '100%';
? ? waitingDiv.style.height = '100%';
? ? waitingDiv.style.background = 'white';
? ? waitingDiv.style.opacity = 0.8;
? ? waitingDiv.style.display = 'flex';
? ? waitingDiv.style.justifyContent = 'center';
? ? waitingDiv.style.alignItems = 'center';

? ? // add the waiting div to the document body
? ? document.body.appendChild(waitingDiv);

? ? // navigate to the link URL after a short delay to allow the waiting message to display
? ? setTimeout(() => {
? ? ? window.location.href = link.href;
? ? }, 1000);
? });
});        

This code attaches an event to every link on the page, which wasn't exactly what I wanted. No matter... a simple follow-up produced what I needed:

The above code is for any link on the page; could you make it a function that I could call on a single link?

In seconds, the code is modified:

function addWaitingOverlay(link) 
? // prevent the default link behavior
? link.addEventListener('click', event => {
? ? event.preventDefault();

? ? // create a div element to display the "waiting" message
? ? const waitingDiv = document.createElement('div');
? ? waitingDiv.innerHTML = 'Please wait...';

? ? // add styles to the waiting div to position it over the entire screen
? ? waitingDiv.style.position = 'fixed';
? ? waitingDiv.style.top = 0;
? ? waitingDiv.style.left = 0;
? ? waitingDiv.style.width = '100%';
? ? waitingDiv.style.height = '100%';
? ? waitingDiv.style.background = 'white';
? ? waitingDiv.style.opacity = 0.8;
? ? waitingDiv.style.display = 'flex';
? ? waitingDiv.style.justifyContent = 'center';
? ? waitingDiv.style.alignItems = 'center';

? ? // add the waiting div to the document body
? ? document.body.appendChild(waitingDiv);

? ? // navigate to the link URL after a short delay to allow the waiting message to display
? ? setTimeout(() => {
? ? ? window.location.href = link.href;
? ? }, 1000);
? });
}        

One small problem: when the next page loads, if the user presses the back button on the browser, the loading message is still covering the previous page. After I send another prompt, ChatGPT responds with an explanation of what needs to change, along with updated code:

To fix this issue, we need to remove the waiting overlay when the user navigates back to the previous page. We can achieve this by adding an event listener to the window object for the beforeunload event, which is fired just before the page unloads. When this event is fired, we can remove the waiting overlay from the document.
// add an event listener to the window object for the beforeunload even
window.addEventListener('beforeunload', () => {
  // remove the waiting overlay from the document
  const waitingDiv = document.querySelector('.waiting-overlay');
  if (waitingDiv) {
    waitingDiv.remove();
  }
});        

You'll notice in the above code, it's relying on a class called waiting-overlay. But it failed to add that class to the div. When I pointed this out, my chat buddy responded:

Sorry. I forgot to add the waiting-overlay class to the div element in the code. Here's the updated code that adds the class:
 waitingDiv.classList.add('waiting-overlay');        

Excellent. Except, I discovered another small issue. The page's navigational drop-down menus were appearing on top of the waiting div. I could easily fix this by modifying the z-index, but I wanted to verify ChatGPT would deliver the right response.

To make the waiting overlay div appear on top of other elements on the page, we need to increase its z-index value. The z-index property controls the stacking order of positioned elements on the page.
Here's the updated code that increases the z-index of the waiting overlay div:
 waitingDiv.style.zIndex = '9999'; // increase the z-index value        

I was loving how ChatGPT would explain exactly what it modified and why.

In this code, we're setting the z-index property of the waiting overlay div to a high value of 9999. This value is higher than the default z-index value of most elements on the page, so the waiting overlay div will appear on top of other elements.

There was one final issue. The beforeunload event is exactly that - an event that fires before the page disappears, which meant the waitingDiv was disappearing too quickly. In short, the solution ChatGPT suggested wasn't going to work.

ChatGPT responded:

You're right, there can be a delay between the beforeunload event firing and the browser navigating to the next page, which can cause the waiting overlay to disappear too early.
To address this, one solution is to add a delay after the link is clicked before removing the waiting overlay. Here's the updated code with the delay:
setTimeout(() => 
      window.location.href = link.href;
      // remove the waiting overlay after a short delay
      setTimeout(() => {
        waitingDiv.remove();
      }, 500);
    }, 1000);        

In the above code, the delay suggested was far to short to solve the problem, but the concept worked, and a simple adjustment to the delay worked just fine.

Whether you think this was the most elegant solution or not, ChatGPT got the job done quickly - with a little help.


Takeaways

There are several ways this simple task could have been accomplished, including:

  • Write it from scratch
  • Google search for code snippets
  • Download Bootstrap and leverage the out-of-the-box Modal

But, assuming you're not already familiar with a framework like Bootstrap, I think all those options would have taken more time. How much more time is hard to say, but this example is a small indication of the time that could be saved over the course of a longer project.

The conversational aspect of this approach blew me away. I didn't have to punch several iterations of questions into Google and hunt for the correct response. It truly felt like I had a coding co-pilot. Better than a co-pilot, actually. ChatGPT was doing the work, and I was just reviewing it.

That said, ChatGPT made mistakes. I thought such a simple task would get delivered in one or two tries, but it required six different prompts (and I had to be able to quickly identify the issues to make it an efficient experience). To be fair, my initial prompt could have been more detailed. Even so, forgetting to attach the class to the div was a surprisingly human mistake.

Smartphones caused us to forget our friends' phone numbers. Spellchecker caused us to forget how to spell complicated words. Navigational systems caused us to forget how to traverse a new city without a map. It seems AI is going to have a similar impact - not just on engineering, but on lots of things.

How big of a concern is this? Humanity didn't forget how to remember a phone number, or spell large words, or figure out which way is north. We have technology doing those things for us, and if that technology went away, we would be okay.

But if the next generation doesn't deeply understand why and how code works, who is going to correct the machines when they make a mistake? Or will they get to a point where they never make a mistake? What happens when everyone is a prompt engineer instead of a coder?

Beyond that, there are the many ethical, legal and privacy concerns of generative AI. But those are questions for another forum.

For now, I've got some gruelingly boring HTML tables I need to go tell ChatGPT to write for me.

Mahesh Kulkarni

Senior Technology Architect

1 年

Good to see you in action Guy.. I remember when I first started programming in visual basic back in 1998 we did a small butterfly animation..there was fulfilment post that exercise.. Excitement too.. If this tool will make the software engineer not wonder but rather lazy as time goes and probably bored down the line.. Then your concerns are so true. This has potential to change the nature of software development for good and very soon for most people to realise what hit them.

回复
Karina Jennings

VP, Marketing Strategy at Providence St. Joseph Health

1 年

What a great case study showing the benefits and downsides of AI. It's just the beginning!

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了