javascript setTimeout() not working [closed]

Hi I'm trying to use the function setTimeout() in javascript except it's not working. Thanks in advance to anyone who can help.

<!DOCTPYE html>
<html>
<head>
    <script>
        var button = document.getElementById("reactionTester");
        var start  = document.getElementById("start");

        function init() {
            var startInterval/*in milliseconds*/ = Math.floor(Math.random() * 30) * 1000;
            setTimeout(startTimer(), startInterval);
        }

        function startTimer() {
            document.write("hey");
        }
    </script>
</head>
<body>
<form id="form">
    <input type="button id=" reactionTester" onclick="stopTimer()">
    <input type="button" value="start" id="start" onclick="init()">
</form>
</body>
</html>

Solution 1:

This line:

setTimeout(startTimer(), startInterval); 

You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:

setTimeout(startTimer, startInterval);

Solution 2:

If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.

i.e. works

setTimeout(function(){ startTimer(p1, p2); }, 1000);

i.e. won't work because it will call the function right away

setTimeout( startTimer(p1, p2), 1000);

Solution 3:

Two things.

  1. Remove the parenthesis in setTimeout(startTimer(),startInterval);. Keeping the parentheses invokes the function immediately.

  2. Your startTimer function will overwrite the page content with your use of document.write (without the above fix), and wipes out the script and HTML in the process.

Solution 4:

If you want to pass a parameter to the delayed function:

    setTimeout(setTimer, 3000, param1, param2);