Countdown Timer with Link Interaction and Final Message Display

Toi Nguyen - Jul 1 - - Dev Community

Here is the JavaScript code to create a download button with a countdown feature as per your request. When the user clicks the button for the first time, a 20-second countdown will start. After the countdown ends, a message will prompt the user to click any link. When the user clicks the link, a second 10-second countdown will begin and finally display the content

1.The HTML part displays the content.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Countdown Download Button</title>
</head>
<body>
<button id="downloadBtn">Start Countdown</button>
<div id="message"></div>
<div id="vnet">content here</div>
</body>
</html>

2.Process CSS for beauty

#downloadBtn {
padding: 10px 20px;
font-size: 16px;
}
#message, #vnet {
margin-top: 20px;
}
#vnet {
display: none;
}

3. JavaScript handles the download button event.
`let downloadBtn = document.getElementById('downloadBtn');
let message = document.getElementById('message');
let vnet = document.getElementById('vnet');

    downloadBtn.addEventListener('click', function() {
        startCountdown(20, function() {
            message.innerHTML = 'Countdown finished. Please click <a href="#" id="anyLink">this link</a> to continue.';
            document.getElementById('anyLink').addEventListener('click', function(event) {
                event.preventDefault();
                startCountdown(10, function() {
                    vnet.style.display = 'block';
                });
            });
        });
    });

    function startCountdown(seconds, callback) {
        let counter = seconds;
        message.innerHTML = `Countdown: ${counter} seconds`;

        let interval = setInterval(function() {
            counter--;
            if (counter >= 0) {
                message.innerHTML = `Countdown: ${counter} seconds`;
            }
            if (counter === 0) {
                clearInterval(interval);
                callback();
            }
        }, 1000);
    }`
Enter fullscreen mode Exit fullscreen mode

Here's how the code works:

  • When the user clicks the "Start Countdown" button, a 20-second countdown begins.
  • After the 20-second countdown ends, a message will appear asking the user to click a link.
  • When the user clicks the link, a second 10-second countdown starts.
  • After the 10-second countdown ends, the content "content here" will be displayed.
.