JavaScript 设置超时循环返回值 [英] JavaScript set timeout loop return value

查看:41
本文介绍了JavaScript 设置超时循环返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能可以 ping 我的服务器以获取特定的数据变化:

I have this function which pings my server for a specific change in data:

function connected() {
  $.ajax({
    success : function(d) {
      if (d.success) {
        // return data
      } else {
        setTimeout(connected, 200);
      }
    }
  });
}

(显然,为了让我的意图更清晰,代码已被精简到最低限度)

(Obviously the code has been stripped to the bare minimum to make my intentions clearer)

我想要做的是在找到时返回一个 bool true,这样我就可以去

What I want to do is return a bool true when it gets found, so I can go

if (connected()) {
  // process data
}

(显然数据存储在一个全局变量中.)

(obviously the data is stored in a global variable.)

有什么办法可以做到这一点吗?

Is there any way to achieve this?

编辑

我可以创建一个暂停"功能:

I could create a 'pause' function:

function pauseScript(ms) {
  ms += new Date().getTime();
  while (new Date().getTime() < ms) {}
}

然后更改我的代码以排除 setTimeout()(并包含一些其他内容)

Then change my code to exclude setTimeout() (and include some other stuff)

function connected() {
  var value;
  $.ajax({
    async: false,
    success : function(d) {
      if (d.success) {
        // set data
          value = true;
      } else {
        pauseScript(200);
        value = connected();
      }
    }
  });
  return value;
}

但是这感觉有点hacky!

However this feels a little hacky!

推荐答案

为了做到这一点,最好在异步模式下继续:

For doing that the best should continue in async mode :

function connected(callback) {
  $.ajax({
    success : function(d) {
      if (d.success) {
        callback();
      } else {
        setTimeout(function() {
          connected(callback);
        }, 200);
      }
    }
  });
}

//Using :
connected(function(){
  //Here i finish my scan result
});

也许,在这种情况下我不太确定,您需要绑定它(我的意思是绑定范围):http://www.robertsosinski.com/2009/04/28/binding-scope-in​​-javascript/

Maybe, i'm not so sure in this case, you will need to bind this (I mean binding scope) : http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/

这篇关于JavaScript 设置超时循环返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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