如果再次调用函数,则取消超时/定时器 --- 去抖动函数 [英] Cancel timout / timer if function called again --- debounce function

查看:42
本文介绍了如果再次调用函数,则取消超时/定时器 --- 去抖动函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个启动超时的函数,但是如果再次调用该函数,则在计时器结束之前,取消原始调用并重新启动计时器.

I want to create a function that starts a timeout, but if the function is called again, before the timer ends, cancel the original call and start the timer again.

我认为我可以做到:

function setTimer() {
   setTimeout(() => {
      // do something
   }, 3000)
} 

...但这不起作用,每次我运行 setTimer() 时,它都不会取消原始调用.

...but that doesn't work, for every time I run setTimer(), it doesn't cancel the original call.

谁能指出我正确的方向?

Can anyone point me in the right direction?

推荐答案

setTimeout 返回一个 ID,您可以使用 clearTimeout() 清除超时.因此,您可以在函数开始时清除现有超时.

setTimeout returns an id you can use to clear that timeout with clearTimeout(). So you can clear the existing timeout at the beginning of your function.

例如,如果你一直点击它会不断重启——如果你不点击它会在 2 秒内完成:

For example if you keep clicking it will keep restarting -- if you don't click it finishes in 2 seconds:

let timerID;

function setTimer() {
  console.log("starting/restarting timer")
  clearTimeout(timerID)
  timerID = setTimeout(() => {
    console.log("finished")
  }, 2000)
}

<p onclick="setTimer()">click to start</p>

这篇关于如果再次调用函数,则取消超时/定时器 --- 去抖动函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆