最近有点闲暇时间了,我就想优化下代码。如下,
对于这段代码,本意是先执行一次,然后隔一段时间后再执行一次
this.getData(token, this.replaceChar(fitnames) || '', this.replaceChar(devices) || '', this.replaceChar(totalFitNames) || '');
const timer = setInterval(() => {
this.getData(token, this.replaceChar(fitnames) || '', this.replaceChar(devices) || '', this.replaceChar(totalFitNames) || '');
}, refleshTime || 2 * 60 * 60 * 1000); // default: 2h
思考下后发现,可以利用闭包,让代码先执行一次。这样就实现了目的。代码也得到了优化,同一块代码不重复出现两次。如下所示
const that = this;
const timer = setInterval((function loadingData() {
that.getData(token, that.replaceChar(fitnames) || '', that.replaceChar(devices) || '', that.replaceChar(totalFitNames) || '');
return loadingData;
})(), refleshTime || 2 * 60 * 60 * 1000); // default: 2h
标签:60,const,replaceChar,setInterval,代码,立即,执行,totalFitNames
From: https://www.cnblogs.com/zhangdezheng/p/17412497.html