存储 setTimeout 稍后调用

Store setTimeout and call it later

看下面的代码:

var timer=setTimeout(function(){increase();}, 8);

这个setTimeout函数会立即执行,但是我想要 它稍后执行。为什么?

示例:

function increase(i)
                 {
                  i++; if(i==100) return;
                  var timer=setTimeout(function(){increase(i);}, 8);
                  }

现在,当某些事情发生时,我需要在另一个函数中停止并退出这个函数:

if (a==b) clearTimeout(timer);

困扰我的是变量定时器被分配,每当 function increase 运行s,但不需要,我认为这是不好的做法。这就是为什么我只需要在函数 运行 之前分配给它一次,并在需要时稍后执行它。

希望您能理解,顺便说一句,这些只是示例,不是我的代码。

因为setTimeout中的delay毫秒为时间单位,所以在你的代码中,你设置你的函数在8ms之后执行,这感觉马上就好了。

如果你想让一个函数的操作改变另一个函数的条件,只需在两个函数的范围内声明一个布尔变量,并根据终止函数改变它的值。

例如,看看这段代码:

var exit = false;

function increase(i) {
    if(i==100 || exit) return;
    setTimeout(function(){ increase(++i) }, 1000);
}

function terminator(a, b){
    exit = (a==b);
}

increase(0);

在这里,如果 terminator 曾经用一对相等的参数调用,例如:

setTimeout(function(){ terminator(true, 1) }, 5000) // timeout of 5 seconds means increase will run 5 times

increase 函数内 setTimeout 的递归调用将不会到达(5 秒后),因为该函数将 return 在到达该行代码之前。

如果 terminator 从未被调用,或使用不相等的参数调用,例如:

setTimeout(function(){ terminator(true, false) }, 5000) // using setTimeout here is just arbitrary, for consistency's sake

increase 只会在完成 100 次递归后超时(换句话说,经过 100 秒后)

希望对您有所帮助!

function increase(i, boolean) {
  i++;
  if (i == 100) return;
  if (boolean) {
    var timer = setTimeout(function() {
      increase(i, true);
      console.log(i);
    }, 8);
  }
}

increase(1,true);

那你多加点论据呢 到函数?

你可以在调用setTimeout的函数外声明一个变量,在调用函数时定义变量为setTimeout;从另一个函数调用 clearTimeout(),变量引用 setTimeout 作为参数。

var timer = null, // declare `timer` variable
  n = 0, // reference for `i` inside of `increase`
  i = 0,
  a = 50,
  b = 50,
  // pass `increase` to `t`, call `increase` at `setTimeout` 
  t = function(fn, i) {
    // define timer
    timer = setTimeout(function() {
      fn(i)
    }, 8)
  };

function increase(i) {
  console.log(i);
  // set `n` to current value of `i` to access `i`:`n` 
  // to access `i` value outside of `t`, `increase` functions
  n = i++; 
  if (i == 100) return;
  t(increase, i); // call `t`
}

increase(i);

// do stuff outside of `t`, `increase`
setTimeout(function() {
  // clear `timer` after `200ms` if `a == b`
  if (a == b) {clearTimeout(timer)};
  alert(n)
}, 200)