如何防止用户短时间内重复操作造成的代码重复执行

举个例子:
button按钮绑定了一个函数,是5s之后打印数字0;如果我们连续点击button按钮多次,会在控制台输出多个0

期望的输出时,控制台最后只输出一个0,是我们最后点击的那一次

思考:假设在真实的项目中,我们有按钮是绑定了一些交互效果的,比如旋转缩放等,如何防止用户重复操作,代码重复执行导致效果累加?

<button  onclick='test()'>点击</button>function test(){   var timer=setTimeout(function(){
      console.log(0);
   }, 5000)
}


莫回无
浏览 703回答 1
1回答

人到中年有点甜

&nbsp; function test(){&nbsp; &nbsp; &nbsp; &nbsp; console.log(0);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function throttle(fun){&nbsp; &nbsp; &nbsp; &nbsp; if(fun.timeoutId) {window.clearTimeout(fun.timeoutId);}&nbsp; &nbsp; &nbsp; &nbsp; fun.timeoutId = window.setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fun();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fun.timeoutId = null;&nbsp; &nbsp; &nbsp; &nbsp; }, 1000);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; throttle(test);&nbsp; &nbsp; throttle(test);&nbsp; &nbsp; throttle(test);&nbsp; &nbsp; throttle(test);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript