如何用另一个函数停止定时器 javascript

how to stop timer with another function javascript

所以我有这个代码

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?
}

函数 timer() 在页面加载时启动,但如果我有一个 stopTime() 按钮并单击它,我如何停止执行第一个函数并阻止它达到 3000 毫秒标记,以及正在提醒 "Out of time"?

使用范围覆盖所有函数的变量。

var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
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?
}

试试这个对你有用

setTimeout 返回的值是一个唯一的 ID,您稍后可以使用它来取消 clearTimeout 的超时。

var timeout;

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

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

function stopTime() {
    clearTimeout(timeout);
}

最好使用来自 React

useRef hook
import {useRef} from 'React';


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


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

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

}