首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >javaScript中的setTimeout无法正常工作

javaScript中的setTimeout无法正常工作
EN

Stack Overflow用户
提问于 2017-07-20 20:21:22
回答 3查看 5.2K关注 0票数 3

我知道这是有答案的,但是!所有的答案在循环中只有一个setTimeout这个问题看起来与我相关,但在我的场景中,脚本中有两个setTimeout,如何通过计时正确地实现这一点!!程序运行正常,但我想要的时间不正确!

代码语言:javascript
复制
function clickDate(i)
{
  setTimeout((function(){
  alert("4");
  })(),2000);
}
function clickButton(i)
{
  setTimeout((function(){
  alert("5");
})(),4000);
}

function doEverything(i)
{
  clickDate(i);
  clickButton(i);
}
for(var i = 0; i < 4; i++)
{
 doEverything(i);
}
EN

回答 3

Stack Overflow用户

发布于 2017-07-20 20:35:08

通过将()添加到函数的末尾,您可以立即调用回调。

您需要传递带超时的回调,系统会为您调用

代码语言:javascript
复制
setTimeout(function(){
alert('hello');
} , 3000);
票数 0
EN

Stack Overflow用户

发布于 2017-07-20 20:36:00

代码语言:javascript
复制
function functionName() {
    setTimeout(function(){ //Your Code }, 3000);
}

试试这个吧。

票数 0
EN

Stack Overflow用户

发布于 2018-09-19 06:49:40

使用setTimeout模拟JavaScript中的异步行为是一种相对常见的做法。但是,由于JavaScript本身的异步特性,为每个函数提供其自己的setTimeout调用是一种反模式。setTimeout看起来像是在强迫JS以一种同步的方式运行,从而产生你看到的4 4 4然后5 5,在for循环的迭代中处于警戒状态。实际上,JS仍然是异步运行的,但是因为您已经使用回调调用了多个setTimeout实例,这些回调被定义为匿名函数,并且在它们各自的函数中作为一个封装范围;您正在封装对JS异步行为的控制,这迫使setTimeout以严格同步的方式运行。作为在使用setTimeout时处理回调的另一种方法,首先创建一个提供您希望发生的计时延迟的方法。示例:

代码语言:javascript
复制
// timer gives us an empty named "placeholder" we can use later
// to reference the setTimeout instance. This is important because
// remember, JS is async. As such, setTimeout can still have methods
// conditionally set to work against it.

let timer 

// "delayHandler", defined below, is a function expression which when
// invoked, sets the setTimeout function to the empty "timer" variable
// we defined previously. Setting the callback function as the function 
// expression used to encapsulate setTimeout provides extendable control
// for us later on however we may need it. The "n" argument isn't necessary,
// but does provide a nice way in which to set the delay time programmatically
// rather than hard-coding the delay in ms directly in the setTimeout function
// itself.

const delayHandler = n => timer = setTimeout(delayHandler, n)

然后,定义要用作事件处理程序的方法。作为附注,为了帮助防止JS代码快速变得混乱,请将事件处理程序方法包装在一个主要的父函数中。要做到这一点,一种(老派的)方法是利用JS揭示模块模式。示例:

代码语言:javascript
复制
const ParentFunc = step => {

  // "Private" function expression for click button event handler.
  // Takes only one argument, "step", a.k.a the index
  // value provided later in our for loop. Since we want "clickButton"
  // to act as the callback to "clickDate", we add the "delayHandler"
  // method we created previously in this function expression.
  // Doing so ensures that during the for loop, "clickDate" is invoked
  // when after, internally, the "clickButton" method is fired as a
  // callback. This process of "Bubbling" up from our callback to the parent
  // function ensures the desired timing invocation of our "delayHandler"
  // method. It's important to note that even though we are getting lost
  // in a bit of "callback hell" here, because we globally referenced 
  // "delayHandler" to the empty "timer" variable we still have control
  // over its conditional async behavior.

  const clickButton = step => {
    console.log(step)
    delayHandler(8000)
  }

  // "Private" function expression for click date event handler
  // that takes two arguments. The first is "step", a.k.a the index
  // value provided later in our for loop. The second is "cb", a.k.a
  // a reference to the function expression we defined above as the
  // button click event handler method.

  const clickDate = (step, cb) => {
    console.log(step)
    cb(delayHandler(8000))
  }

  // Return our "Private" methods as the default public return value
  // of "ParentFunc"

  return clickDate(step, clickButton(step))
}

最后,创建for循环。在循环中,调用"ParentFunc“。这将启动setTimeout实例,并在每次运行循环时运行。示例:

代码语言:javascript
复制
 for(let i = 0; i < 4; i++) {

   // Within the for loop, wrap "ParentFunc" in the conditional logic desired
   // to stop the setTimeOut function from running further. i.e. if "i" is 
   // greater than or equal to 2. The time in ms the setTimeOut was set to run
   // for will no longer hold true so long as the conditional we want defined
   // ever returns true. To stop the setTimeOut method correctly, use the 
   // "clearTimeout" method; passing in "timer", a.k.a our variable reference 
   // to the setTimeOut instance, as the single argument needed to do so.   
   // Thus utilizing JavaScript's inherit async behavior in a "pseudo" 
   // synchronous way.

   if(i >= 2) clearTimeout(timer)
   ParentFunc(i)
 }

最后要注意的是,尽管实例化setTimeOut是模拟异步行为的常见做法,但在处理初始调用/执行和用作事件处理程序的方法的所有后续生命周期计时时,要遵守利用Promise。使用Promises来解析事件处理程序可以确保方法的执行时间与它们被调用的场景相关,并且不会局限于类似于"setTimeOut“方法中定义的严格的时间行为。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45214558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档