Skip to content Skip to sidebar Skip to footer

Javascript || Angular2/6: Calling Setinterval Multiple Times But Last Timerid Is Not Stopping Even Though Clearinterval Called

Requirement: User scans multiple job numbers, for each job number , I need to call one API and get the total job details and show it in a table below the scanned text box. User d

Solution 1:

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];

functionscannableJobs () {
	return globalsJobs;
}

functiongenerateAutoCancellableInterval(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);
<buttonid="removejobs">
  clear jobs
</button><divid="infobox"></div></div>

Post a Comment for "Javascript || Angular2/6: Calling Setinterval Multiple Times But Last Timerid Is Not Stopping Even Though Clearinterval Called"