如何停止定时器与另一个函数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?
}
函数计时器()开始作为页面加载,但如果我有一个按钮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);
}
相关文章:
- 从函数JavaScript返回不可变数组/对象
- 将对象传递给函数.JavaScript
- 如何定义const函数javascript(语法糖)
- 新的日期函数javascript
- TypeError:this.getAttribute不是一个函数-javascript
- 从函数javascript发送变量
- 扩展自容器函数Javascript
- 从内部函数javascript内部分配外部函数的对象
- 使用函数JavaScript中的函数
- 在这里使用回调函数(JavaScript)有什么好处吗
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 将“e”传递给一个新函数 - javascript
- 调用函数中的一个函数——Javascript
- 传递的变量不适用于我的函数-Javascript
- 如何将类方法设置为等于多个函数?-Javascript
- 显示php中的函数javascript
- 如何使用php代码创建函数Javascript弹出框
- 未调用的外部函数-javascript
- 如何在类中运行函数.Javascript
- 关闭mouseover上的一个函数——Javascript,jQuery