简体   繁体   中英

JS: need explanation about setTimeout() behavior

I have 2 button. First one runs the reminder, another stops it:

<input type="range" id="range" min="1" max="480" onInput="syncValues('intrvl',this);" />
<input type="text" id="intrvl" value="0.07" onInput="syncValues('range',this);" />

Here is the script (the live version is accessible on Plunker: http://plnkr.co/edit/9kslSw6lyflIkMTanCrA ):

function syncValues(inpToId, inpFrom) {
  if (!inpFrom) inpFrom = document.getElementById('intrvl');
  document.getElementById(inpToId).value = inpFrom.value;
}
window.onload = function() {
  syncValues('range');
  var makeDecition = (function() {
    var tm,
      stp = false,
      gotm = false,
      sttm = function(cancel) {
        var min = document.getElementById('intrvl').value;
        tm = setTimeout(makeDecition, min * 60 * 1000);
      };
    return function(cancel) {
      console.dir(cancel);
      if (cancel) {
        stp = false;
        clearTimeout(tm);
      } else {
        if (gotm) {
          if (!stp)
            if (!confirm("Go on?")) gotm = null;
        } else {
          stp = false;
          gotm = true;
        }
        if (gotm !== null) sttm();
      }
    };
  }());
  document.getElementById('start').onclick = function(event) {
    makeDecition();
    event.currentTarget.disabled = true;
  };
  document.getElementById('stop').onclick = function(event) {
    makeDecition();
    document.getElementById('start').disabled = false;
    makeDecition(true);
  };
};

I want that after clicking on the Stop button the timeout will be removed and script will terminated immediately. But it show me confirm istead. I checked what happens after calling makeDecition(true) and found that the function doesn't get the cancel param, first, as mentioned above, it calls confirm and only after it the param comes. Can anybody explain how to fix it and why it happens?

在“停止”处理程序的开始,您对“ makeDecition”函数进行了无参数的无参数调用:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM