[JavaScript] How to use setInterval gracefully

I want to execute the code every once in a while


The simplest timer is as follows ,

setInterval(function () {
    
    
    // do sth...
}, 1000)

There is no problem with writing this way,
but at first, I had to wait a second silly for the code to be called for the first time.

Maybe you think it's okay, but it's only a second.
But if this time interval is very long, such as one minute, ten minutes, or even one hour, then something goes wrong.


The solution is simple, as follows:

// 1.定义函数
function demo() {
    
    
	// do sth...
}
// 2.执行一次
demo();
// 3.打开定时器
setInterval(demo, 1000);

// 1. Define the function
// 2. Execute once
// 3. Turn on the timer The
problem is solved!
Although the problem is solved, it is not elegant enough to look uncomfortable!


How to do it?
At this time the closure is about to come into play:

The code is elegant and refreshing!

setInterval((function demo() {
    
    
    // do sth...
    return demo;
})(), 1000);

Execute it immediately before passing the parameters, and then return to yourself.

Perfect solution.

Guess you like

Origin blog.csdn.net/qq_16181837/article/details/104851070