Home javascript Problem with SetTimeout: function executes without delay

Problem with SetTimeout: function executes without delay

Author

Date

Category

The script executes the function without delay, what’s the error?

& lt; script & gt;
  function nummain (num) {
    document.write ('wait' + num + 'seconds');
    num = num - 1;
    if (num == 0) {
      main (1);
    } else {
      document.setTimeout (nummain (num), 1000);
    }
  }
& lt; / script & gt;
& lt; script & gt;
  nummain (30)
& lt; / script & gt;

Answer 1, authority 100%

Function and delay are used as arguments to the setTimeout function. You are not specifying a function, but its result, the so-called. recursion. This is where execution comes in without delay. Try this:

function nummain (num) {
  document.write ('wait' + num + 'seconds');
  num = num-1;
  if (num == 0) main (1);
  else setTimeout (function () {nummain (num);}, 1000);
}

Answer 2

1) No need to write document. before setTimeout

2) The called function must be passed as a string, in other words, wrapped in quotes

setTimeout ("nummain (" + num + ")", 1000);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions