如何使用setTimeout()

时间:2018-05-22 08:32:46

标签: javascript settimeout break

这是我的代码:

mylabel:{
    var myTimeout = setTimeout(function(){
      SpinnerDialog.hide();
      alert("Timeout");
      break mylabel;
    }, 10000);
    connectWifi();
  }

如果Wi-Fi网络不可用,我有一个可以挂起的功能connectWifi()所以我想在一段固定的时间后停止它。此函数包含其他函数,它执行以下操作:

function(){
    function(){
      function(){

      }
    }
  }

当调用超时函数时,我收到一条错误消息"未定义标签"

编辑:我的目标不是停止超时功能就是停止connectWifi功能。

如果你想在这里看到connectWifi()函数是代码(我使用以下cordova插件:WifiManager,autowifi和CordovaMqTTPlugin):

    function connectWifi() {
  cordova.plugins.WifiManager.isWifiEnabled(function (err, wifiEnabled) {
    console.log("isWifiEnabled result : " + wifiEnabled);
    if (wifiEnabled == false) {
      cordova.plugins.WifiManager.setWifiEnabled(true, function (err, succes) { console.log(err, succes); });
      console.log("-- Wifi Enabled --");
    }
  });
  window.plugins.autowifi.setssid(s_SSID, s_PASS);
  SpinnerDialog.show(null, "Connexion en cours...", true);
  window.plugins.autowifi.connect(function (scc) {
    wifiReady = true;
    SpinnerDialog.hide();
    console.log("Wifi connected");
    console.log("debut fonction connectMQTT");
  if (wifiReady) {
    //Connexion MQTT
    SpinnerDialog.show(null, "Acces au serveur en cours...", true);
    cordova.plugins.CordovaMqTTPlugin.connect({
      url: _url, //a public broker used for testing purposes only. Try using a self hosted broker for production.
      port: _port,
      clientId: _clientId,
      success: function (s) {
        alert("Connexion reussie !");
        connected = true;
        console.log(JSON.stringify(s));
        document.getElementById("connect").style.display = "none";
        document.getElementById("disconnect").style.display = "initial";
        document.getElementById("activity").innerHTML += "--> Success: you are connected to, " + _url + ":" + _port + "<br>"
        SpinnerDialog.hide();
        SpinnerDialog.show(null, "Recuperation des donnees...", true);
        //Abonnement MQTT au topic
        cordova.plugins.CordovaMqTTPlugin.subscribe({
          topic: _topic,
          qos: 0,
          success: function (s) {
            SpinnerDialog.hide();
            document.getElementById("activity").innerHTML += "--> Success: you are subscribed to the topic, " + _topic + "<br>"

            cordova.plugins.CordovaMqTTPlugin.listen(_topic, function (payload, params, topic, topic_pattern) {
              //params will be an empty object if topic pattern is NOT used. 
              document.getElementById("activity").innerHTML += "--> Payload for" + topic + " topic: " + JSON.stringify(payload) + "<br>"
            })
          },
          error: function (e) {
            SpinnerDialog.hide();
            document.getElementById("activity").innerHTML += "--> Error: something is wrong when subscribing to this topic, " + e + "<br>";
            document.getElementById("subscribe").style.display = "initial";
            document.getElementById("unsubscribe").style.display = "none";
            //alert("err!! something is wrong. check the console")
            console.log(e);
          }
        });
        //---------------------

      },
      error: function (e) {
        SpinnerDialog.hide();
        connected = false;
        //document.getElementById('status').innerHTML = "déconnecté";
        //document.getElementById('statusbar').className = "w3-bar w3-red"
        alert("Echec de la connexion, assurez-vous que vous êtes connectés en wifi au serveur puis veuillez reessayer");
        document.getElementById("activity").innerHTML += "--> Error: something is wrong,\n " + JSON.stringify(e) + "<br>";
        document.getElementById("connect").style.display = "initial";
        document.getElementById("disconnect").style.display = "none";
        alert("err!! something is wrong. check the console")
        console.log(e);
      },
      onConnectionLost: function (e) {
        SpinnerDialog.hide();
        console.log(JSON.stringify(e));
        connected = false;
        //document.getElementById('status').innerHTML = "déconnecté";
        //document.getElementById('statusbar').className = "w3-bar w3-red"
        alert("Vous avez ete deconnecte");
        document.getElementById("activity").innerHTML += "--> You got disconnected";
        document.getElementById("connect").style.display = "initial";
        document.getElementById("disconnect").style.display = "none";
      }
    });
    //--------------------
  } else {
    console.log("wifiReady false");
  }
  });
}

(很少有东西是法语,因为我是法国人)

2 个答案:

答案 0 :(得分:0)

break出现在标记语句中声明的匿名函数中,但它本身不是语句的一部分。这就是为什么你不能从匿名函数跳转到标签。

讨论您实际问题的一些问题(如何从计时器取消活动):

你会发现此时没有简单的内置方式。

答案 1 :(得分:0)

不要使用大量代码,而是将其分成可重复使用的小块:

function promisify(fn) {
  return function() {
    return new Promise((resolve, reject) => {
     fn((err, res) => err ? reject(err) : resolve(res));
    });
  }
}

const isWifiEnabled = promisify(cb =>  cordova.plugins.WifiManager.isWifiEnabled(cb));    

const enableWifi = promisify(cb => cordova.plugins.WifiManager.setWifiEnabled(true, cb));

const connect = options => promisify(cb => cordova.plugins.CordovaMqTTPlugin.connect({
  ...options,
  success: res => cb(null, res),
  error: cb,
})();

现在我们已经得到了承诺,我们可以轻松地将它们链接起来并与之合作:

async function ensureWifi() {
  if(!await isWifiEnabled()) await enableWifi();
}

要实现超时,我们只使用Promise.race:

function cancelAfter(promise, time) {
  const timeout = new Promise((_, reject) => setTimeout(reject, time, new Error("Timeout")));
  return Promise.race(promise, timeout);
}

所以我们可以这样做:

(async function() {
  try {
    // show loaders here
    await cancelAfter(ensureWifi(), 1000);
    await cancelAfter(connect({ /*...*/ }), 200);
    // All done
 } catch(error) {
    // Api error or timeout
 }
})()