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

how to stop timer with another function javascript

本文关键字:函数 javascript 另一个 何停止 定时器      更新时间:2023-09-26

所以我有这个代码

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

函数计时器()开始作为页面加载,但如果我有一个按钮stopTime(),我点击它,我如何阻止第一个函数执行,并阻止它从击中3000毫秒的标记和警报"超时"?

使用一个作用域覆盖所有函数的变量

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

试试this it will Work For you

最好使用React中的useRef钩子

import {useRef} from 'React';

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

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

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

var timeout;
function timer () {
    timeout = setTimeout(/* ... */);
}
function resetTime() {
    stopTime();
    timer();
}
function stopTime() {
    clearTimeout(timeout);
}