KoolKeith
KoolKeith

Reputation: 45

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.

let timerId = setInterval(function () {
        document.getElementById("seconds").innerHTML = pad(++sec % 60);
        document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
    }, 1000);
    function myFunction() {
  alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
} 

Upvotes: 1

Views: 1276

Answers (2)

Punith Mithra
Punith Mithra

Reputation: 628

This should solve your problem.

var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");

timeElement.innerHTML = timeSpent;

let timerId = setInterval(function () {
        var currentTime = new Date().getTime();
        timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
        timeElement.innerHTML = timeSpent;
    }, 1000);
    
function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

  function alertFn(){alert(timeSpent)}
 document.getElementById("rightButton").addEventListener('click',alertFn);

 document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>

Upvotes: 1

Saba Turdzeladze
Saba Turdzeladze

Reputation: 19

First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.

Your code should look something like this

let timerId;
function displayTime() {
    timerId = setInterval(() => {
        // your code

    }, 1000);
}

document.querySelector('button').addEventListener('click', displayTime)

Upvotes: 1

Related Questions