Thursday, 11 May 2017

Recursive function with timeout to prevent stack call exceeded

I am trying to find any and all images an any object of any depth with a recursive function, but as expected it will give a Maximum call stack size exceeded error in some applications. The solution here said to wrap the recursive function in a setTimeout but then it appears the the function doesn't work an anymore.

const resultsReg = []
const resultsTimeout = []
const obj = {
    key : {
        foo: 'bar.jpg'
  }
}

function findImages(object, results) {
  for (var key in object) {
    if (typeof object[key] === 'string') {
      if (object[key].match(/\.(jpg)$/i) && !results.includes(object[key]) && results.length < 9) results.push(object[key]);
    }
    else if (typeof object[key] === 'object') {
      findImages(object[key], results); // this works, but in some applications will give Maximum call stack size exceeded error
    }
  }
}

function findImagesTimeout(object, results) {
  for (var key in object) {
    if (typeof object[key] === 'string') {
      if (object[key].match(/\.(jpg)$/i) && !results.includes(object[key]) && results.length < 9) results.push(object[key]);
    }
    else if (typeof object[key] === 'object') {
      setTimeout(function() {
        findImagesTimeout(object[key], results) // this fails
      }, 0)
    }
  }
}

findImages(obj, resultsReg)
findImagesTimeout(obj, resultsTimeout)
console.log(resultsReg)
console.log(resultsTimeout)

output:

[ 'bar.jpg' ]
[]

Am I doing something wrong?



via platizin

No comments:

Post a Comment