setInterval-如何仅触发一次? [英] setInterval - How to fire only once?

查看:122
本文介绍了setInterval-如何仅触发一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有这段代码片段,即使我选择了一段时间,它们也会触发一些代码.

Hello I have this snippet of code that will fire some even after time that I choose.

问题是,例如,如果我放3秒,它将每3秒触发一次,我需要的是3秒后仅触发一次.

The problem is that if, for example I put 3 seconds it will fire every 3 seconds, what I need is it to fire only once after 3 seconds.

function playSound(timeLeft){
   var sendDataTimeout = function(){
      alert('OK');
   }
   var intervalReference = 0;
   clearInterval(intervalReference);
   intervalReference = setInterval(sendDataTimeout, timeLeft);
}

推荐答案

改用setTimeout,它的工作原理几乎相同,但只会触发一次.您有clearTimeoutsetTimeout,所以它与setInterval

Use setTimeout instead, it works almost the same but will only fire once. You have clearTimeout and setTimeout so its very similar to setInterval

function playSound(timeLeft){
   var sendDataTimeout = function(){
      alert('OK');
   }
   setTimeout(sendDataTimeout, timeLeft);
}

您不再需要使用clearTimeout.但仅供参考,它存在并且与clearInterval相同.

You don't have to use clearTimeout anymore. But FYI it exist and works the same as clearInterval.

这篇关于setInterval-如何仅触发一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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