Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何在 JavaScript 中第一次无延迟地执行 setInterval 函数 #61

Open
wangjing013 opened this issue Sep 29, 2021 · 0 comments

Comments

@wangjing013
Copy link
Owner

wangjing013 commented Sep 29, 2021

setInterval 应该是比较高频. 有些场景需要执行定时器之前先执行一次 setInterval 函数.

通常可以使用下面的方式.

在执行 setInterval 之前执行

        let count = 1;
        function exampleFunction() {
            console.log('Function Executed! ' + count);
            count = count + 1;
        }
      
        function noDelaySetInterval(func, interval) {
            func();
            return setInterval(func, interval);
        }
      
        function startSetInterval() {
            noDelaySetInterval(exampleFunction, 3000);
        }

在 setInterval 函数中使用立即调用函数

function startSetInterval() {   
    let count = 1;
      
    setInterval(function exampleFunction() {
        console.log('Function Executed! ' + count);
        count = count + 1;
  
        return exampleFunction;
    }(), 3000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant