简体   繁体   中英

setTimeout only executes once

Why is the setTimeout only being called once?

repeatSubscriber = function(observer) {
        observer.next('first');
        (function() {
            setTimeout(() => {
                observer.next('repeating timed resp');
            }, 3000);
        }());
    };

Prints:

first
repeating timed resp

setTimeout()仅应触发一次-您需要的是setInterval()

Because it should:

setTimeout() sets a timer which executes a function or specified piece of code once after the timer expires.

More at MDN

What you are looking for is setInterval()

 repeatSubscriber = function(observer) { observer.next('first'); (function() { setInterval(() => { observer.next('repeating timed resp'); }, 3000); }()); }; 

Because it worked like this its in the function nature,

If you need repeated call you need setInterval function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM