jQuery - 暂时禁用功能然后再次启用它

问题描述 投票:0回答:2

我想禁用运行中的函数,并在某些超时后启用它。

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

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

可以这样做吗?

javascript jquery
2个回答
1
投票

我希望它会对你有所帮助。

function messages() {

      var main = setInterval(function() {


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

     
  

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


      }, 20000);  // It's looping every 20 sec
        
     
    setTimeout(function() {
        clearInterval(main);
    }, 60000);  // stop again it after 60 sec
        
 
    setTimeout(function() {
         messages();
    }, 120000); // start again it after 120 sec
        
    }
    
    messages();

更新


1
投票

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

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

这会有用吗?希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.