Why is my code showing "Timeout exceeded, make sure your code is executed no more than 1500ms."

Viewed 56

I am trying to execute this piece of JavaScript code, but unfortunately it outputs "Timeout exceeded, make sure your code is executed no more than 1500ms." What is the problem with this code?

console.log('hlo')
let obj = {
  bird: "yguhdjn",
  color: 'blue',
  eat:'insect'
}
function GetObjectKeys(obj, keys)
{
for (let key in obj)
{ if (typeof obj[key] == "object")
{ 
  GetObjectKeys(obj[key], keys);
}
 else {
        keys.push(key);
       }
return keys;

  console.log(obj[key])
}
}
1 Answers

You are calling your function recursively. What this means is that inside your function GetObjectKeys(), you are calling that very same function GetObjectKeys().

Effectively, it is a neverending loop and there is no way in your code for that loop to terminate, so eventually it will run out of time.

You are also trying to test whether a property of the obj you pass in is an object itself. But your test data does not include an object, so in my sample code below, I added two objects to the test data.

The structure of the code with the brackets is very confusing, so it is difficult to see what should happen. If you format the code properly with good indentation, then you will see that the final console.log will never be called.

When asking a question on Stack Overflow, it is better to add your code to the question by using the code snippet button <> which is in the toolbar of the question editor. After entering your code, you can click tidy to format the code, and run to test it.

Please have a look at minimum reproducible example for a full explanation of how to ask good questions.

console.log('Hello')

let obj = {
  bird: "yguhdjn",
  color: 'blue',
  eat: [
    'insect',
    'seed',
    'berry',
  ],
  can: [
    'fly',
    'swim',
  ]
}

function GetObjectKeys(obj) {
  const keys = [];

  for (let key in obj) {
    if (typeof obj[key] === "object") {
      console.log("object:", key, obj[key]);
    } else {
      keys.push(key);
    }
  }

  return keys;
}

console.log("not objects:", GetObjectKeys(obj));

Related