功能分类: Control Applab JavaScript 少儿编程
取消一个通过 setTimeout() 方法设置的定时执行,指定 timeout 为原 setTimeout() 返回值。
一个定时执行功能设置后,通常还需要一个可以取消的功能。使用 clearTimeout() 方法,并将 setTimeout(function, milliseconds) 返回值作为参数使用,就可以将设置的定时执行取消。
// 设置 Timeout 并立即取消
var t = setTimeout(function() {
  console.log("The timeout has completed");
}, 10000);
console.log("Timer ID: " + t);
clearTimeout(t);
示例代码:用户按钮控制 通过页面控件 timeOut 设置与取消。
// 通过页面控件 timeOut 设置与取消
textLabel("instructions", "Click Start to begin a 3 second timeout timer, then Stop to prevent it from completing");
textLabel("status", "");
button("startButton", "Start");
button("cancelButton", "Stop");
var t;
onEvent("startButton", "click", function(){
  t = setTimeout(function() {
    setText("status", "The timer completed!");
   }, 3000);
   setText("status", "Timer started!");
   console.log("Timer ID: " + t);
});
onEvent("cancelButton", "click", function(){
  if(t) {
    clearTimeout(t);
    setText("status", "The timer has been cancelled.");
  } else {
    setText("status", "You need to start the timer before you can stop it :)");
  }
});
clearTimeout(timeout);
| 名称 | 类型 | 必需 | 参数描述 | 
|---|---|---|---|
| timeout | number | Yes | 指定要取消的定时执行 id 唯一标识。 | 
没有返回值。