6

So I have this code

function timer()
{
     setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds
}
function resetTime()
{
     timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want
}
function stopTime()
{
     //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message?
}

the function timer() starts as the page loads but if I have a button for stopTime() and I click on it, how do I stop the first function from executing and stop it from hitting the 3000 millisecond mark and alerting "Out of time"?

1
  • You need to name your timer to a global var Commented May 25, 2015 at 5:13

4 Answers 4

7

Use a variable with scope over all of your functions.

var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
Sign up to request clarification or add additional context in comments.

Comments

1
var timer;

function timer()
{
    timer = setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds
}
function resetTime()
{
    clearTimeout(timer);
     timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want
}
function stopTime()
{
     //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message?
}

try this it will Work For you

1 Comment

@colecmc sorry my mistake
0

Its best to use the useRef hook from React

import {useRef} from 'React';


const function =()=>{
   const timerRef = useRef();


   const timerFunction =()=>{
      timerRef.current = setTimeout(()=>{
      //Your Code
      },5000);
`

  const clearTimerFunction =()=>{
       clearTimeout(timerRef.current);
      }

}

1 Comment

There is nothing to do with react in this question. The question is about javascript not react.
-1

The value returned from setTimeout is a unique ID that you can use later to cancel the timeout with clearTimeout.

var timeout;

function timer () {
    timeout = setTimeout(/* ... */);
}

function resetTime() {
    stopTime();
    timer();
}

function stopTime() {
    clearTimeout(timeout);
}

Comments

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.