0

I'm trying to make a recursive loop using SetTimeout, but when I call the wait() method it doesn't wait for the loop to finish to return true, and since it doesn't return true it falls to else because it didn't find the expected value.

The wait() function is executed, but does not wait for the loop to terminate.

The number 100 represents speed, and the number 10 represents the amount of iteration I want to happen.

EDIT: I'm using internet explorer, and Promise doesn't work for me

    function wait(time, limit) {
        if (limit < 0) return true
        setTimeout(function () {        
            wait(time, --limit)
        }, time);  
    }
    
    if (wait(100, 10)) {
        console.log('success')
    } else {
        console.log('error')
    }

How to wait for the loop to be finished and then fall to the IF?

megaultron
  • 399
  • 2
  • 15
  • I'm unsure whether to mark this as an *exact* duplicate, but what you ultimately want is *probably* [this](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep). Basically you need to "promisify" your `setTimeout`, because currently `wait` only ever returns `true` or `undefined`, and the return value of the `wait` within the `setTimeout` is ignored entirely. – David Dec 21 '21 at 12:54
  • Sorry, I put in the edit of my question that I'm using internet explorer and I can't use a promise – megaultron Dec 21 '21 at 12:56
  • Perhaps combined with [this](https://stackoverflow.com/questions/36016327/how-to-support-promises-in-internet-explorer-11) too then. – David Dec 21 '21 at 12:57
  • ok i will try, thanks – megaultron Dec 21 '21 at 13:11
  • [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#browser_compatibility) is an object of ES6 syntax and is not supported in IE. Therefore, such a problem arises. The case mentioned by David also explains the reason very well, and I think it should solve your problem. – Xudong Peng Dec 22 '21 at 08:34

0 Answers0