“This is the 28th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

The introduction

Have you ever had the experience of suddenly realizing that something you held for a long time was wrong?

I remember that setInterval executes the logic immediately after it is defined, so I omitted the second step (” execute logic A immediately “) when implementing the logic below. This omission caused me a bug

Out of the bug, to remedy, attitude can not lose!

Bronze level

For the simplest fix, which is the one we often use, the code is as follows:


function fun(){}
fun();
setInterval(fun, 1000);

Copy the code

Yes, simple and unpretentious as that!

Diamond level

Since it’s a diamond grade, it’s got to be something, or it’s gonna be a waste of time.

The bronze level implementation above has a catch: there is no way to ensure that only one timer executes this logic at a time. So let’s encapsulate it again:

let timer = null;
function func(){}
function mainFun(callback, time){
	callback();
	return setInterval(callback, time);
}
timer && clearInterval(timer);
timer = mainFun(func, 1000);

Copy the code

Star yao level

Returns the target function itself using the target function.

let timer = null;
function func(){}
timer && clearInterval(timer);
timer = mainFun(func(), 1000);
Copy the code

Well, the code has gone up a notch.

King level

If you need to execute immediately, why not use self-executing functions?

let timer = null;
timer && clearInterval(timer)
timer = setInterval((function func () {}) (),1000);
Copy the code

The logic is the same, but for some reason it feels a bit fancy. ^-^

conclusion

In fact, I still do not understand why I have such a false memory, and did not find correction for so long.

Making mistakes is not terrible, terrible is not aware of making mistakes!

Blacksmith also need their own hard, do not look at others’ implementation of how lofty, in fact, are some reasonable combination of basic knowledge of the results of use, as long as your foundation is good enough, that even in the face of a simple code can play a different pattern!

~

Thanks for reading!

~

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!