首页 > 解决方案 > jQuery - 暂时禁用功能然后再次启用它

问题描述

我想禁用功能运行并在特定超时后启用它。

例如,我想在一段时间后停止第一个脚本循环,然后重新启动它。

JS

// Script that loops

function messages() {

  setInterval(function() {

    setTimeout(function() {
      alert("Hello!");
    }, 2000);  

    setTimeout(function() {
      alert("I said hello!");
    }, 10000);  

  }, 20000);  // It's looping every 20 sec

}

// Script with timeout to stop the loop

setTimeout(function() {
  messages.stop();
}, 60000);  // Stop it after 60 sec

setTimeout(function() {
  messages.start();
}, 120000);  // Start again it after 120 sec

这可以做到吗?

标签: javascriptjquery

解决方案


如果它在循环内,你不能:

// the start method turns a variable to true for example in the inner function scope
if (start) {
  setTimeout((data) => data, 25000);
}

这行得通吗?希望能帮助到你。


推荐阅读