具有超时的递归函数以防止超出堆栈调用

时间:2017-05-11 13:09:27

标签: javascript node.js recursion

我试图用递归函数找到任何和所有图像任何深度的任何对象,但正如预期的那样,它会在某些应用程序中给出一个超出最大调用堆栈大小的错误。解决方案here表示将递归函数包装在setTimeout中但是看起来该函数不再起作用了。

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)

输出:

[ 'bar.jpg' ]
[]

我做错了吗?

0 个答案:

没有答案