2

I wrote a timer code via JavaScript. I want to stop this timer when I click on a button, and restart it by double clicking the same button, however, it currently only works once.

Here is the code:

let pElement = document.createElement('p');
document.body.appendChild(pElement);

let liveTimer = () => {
  let date = new Date();
  let onlineTime = date.toLocaleTimeString();

  pElement.innerHTML = onlineTime;
};

let setI = setInterval(liveTimer, 1000);

function stopTime() {
  clearInterval(setI);
}

function startTimer() {
  setInterval(liveTimer, 1000);
}
<button onclick="stopTime()" ondblclick="startTimer()">click me</button>

1

1 Answer 1

3

You forgot to set the interval-Id the second time you are calling setInterval inside the startTimer function.

Just because you set the value here let setI= setInterval(liveTimer,1000);, doesn't mean that the value will get refreshed when you do setInterval(liveTimer,1000);. This will return a different value that you need to store inside a variable.

let pElement = document.createElement('p');
document.body.appendChild(pElement);


let liveTimer = () => {
  let date = new Date();

  let onlineTime = date.toLocaleTimeString();

  pElement.innerHTML = onlineTime;

};

let setI = setInterval(liveTimer, 1000);

function stopTime() {
  clearInterval(setI);
}


function startTimer() {
  setI = setInterval(liveTimer, 1000);
}
<button onclick="stopTime()" ondblclick="startTimer()">click me</button>

Sign up to request clarification or add additional context in comments.

7 Comments

Come to think of it, it is a typo-type question and can be closed
I really appreciate it
@mplungjan Just because the solution sounds obvious once its been stated, doesn't mean that the problem was a typo. I would say that problem was closer to a syntax error in the sense that the user didn't know that value doesn't get bound to the interval.
There is no "close as syntax error" to choose. Typo-type covers this too
@mplungjan Why would it fall under the same category? The problem may have been caused by lack of JavaScript knowledge (without any offense to the OP). Isn't this one of the main reason why SO exists?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.