javascript || Angular2/6: Calling setInterval multiple times but last timerId is not stopping even though clearInterval called

怎甘沉沦 提交于 2019-12-02 05:18:19

The following code will create and auto cancellable interval when there is not more jobs to scan, this principle will do the trick that you need, please ask if you have any doubt.

Use the Clear Jobs button to remove jobs into the array that keep all the existing jobs

var globalsJobs = [1,2,3,4];

function scannableJobs () {
	return globalsJobs;
}

function generateAutoCancellableInterval(scannableJobs, intervalTime) {
	var timer;
	var id = Date.now();
  
  timer = setInterval(() => {
  	console.log("interval with id [" + id + "] is executing");
    var thereUnresponseJobs = scannableJobs();
    if (thereUnresponseJobs.length === 0) {
    	clearInterval(timer);
    }
  }, intervalTime)
}

const btn = document.getElementById('removejobs');
const infobox = document.getElementById('infobox');
infobox.innerHTML = globalsJobs.length + ' jobs remainings'

btn.addEventListener('click', function() {
	globalsJobs.pop();
  infobox.innerHTML = globalsJobs.length + ' jobs remainings'
}, false);

setTimeout(() => generateAutoCancellableInterval(scannableJobs, 1000), 0);
setTimeout(() => generateAutoCancellableInterval(scannableJobs, 1000), 10);
<button id="removejobs">
  clear jobs
</button>

<div id="infobox">
  
</div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!