1

I'm trying to figure out how to run a chunk of code a few seconds after a user presses a submit button on a form. My test page is waiting the right amount of time and properly executing the chunk of code, but instead of waiting for the submit event, it seems to be starting my timer on page load. It seems like I am not using .addEventListener in the right way; does anyone see my problem? I'm using the latest version of Firefox, not IE6 or anything like that.

<html>
<head>
    <title>Listener Test</title>    
</head>
<body>
    <form id="travelInfo">
        Depart: <input type="text" name="depart" value="BWI" id="depart"><br />
        Arrive: <input type="text" name="arrive" value="LAX " id="arrive"><br />
        <input type="submit" name="submit" value="Send Form" id="Submit">
    </form>

    <script type="text/javascript">
        window.addEventListener('submit', timeFunction(), true);
        function timeFunction()
        {
            var t=setTimeout("handler()",3000);
        }
        function handler()
        {
            alert("Hello");
        }       
    </script>
</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kladky
  • 81
  • 1
  • 7

1 Answers1

4

Replace

window.addEventListener('submit', timeFunction(), true);

with

window.addEventListener('submit', timeFunction, true);

See the difference between invoking a function and referencing it in my other answer.

Also, instead of doing

setTimeout("handler()", 3000);

which will basically be eval'd when the timeout occurs, you could pass a reference to the handler function directly to setTimeout. Notice the absence of quotes and the parentheses.

setTimeout(handler, 3000);
Community
  • 1
  • 1
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • I had tried that, but when I do that it seems that the function isn't called at all, even when I do click the submit button. Thoughts? – Kladky Jan 18 '12 at 21:39
  • When you submit the form, the page changes. It can't show an alert 3 seconds later because the page has changed. – Niet the Dark Absol Jan 18 '12 at 21:40
  • @user1130337 - Like Kolink said the page is changing. You have to stop the submit event from happening or postpone it until the timeout occurs. See this [example](http://jsfiddle.net/Zk7kY/) for how to prevent the form from submitting. – Anurag Jan 18 '12 at 21:44