user2076400
user2076400

Reputation: 27

setTimeout being called repetitively than after an interval of 3sec

Why is the function being called repetitively than after 3 sec?

<button onclick="myFunction()">Try it</button>

<script>
    function myFunction()
    {
        alert("hello");
        setTimeout(myFunction(),3000);
        // setTimeout(function(){ alert("Hello") }, 3000);
     }
</script>

Upvotes: 0

Views: 203

Answers (3)

Micha&#235;l Nguyen
Micha&#235;l Nguyen

Reputation: 363

When you use setTimeout, you need to give a callback function, not calling the callback! XD Instead of:

setTimeout(myFunction(), 3000);

You must write:

setTimeout(myfunction, 3000);

Remember that adding () to the end will call the function. In your example, you are doing an infinite loop.

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Look at this code

setTimeout(myFunction(),3000);

The () after myFunction is saying, call myFunction and store whatever it returns. After 3 seconds call that.

What you need to do is NOT call the function, but store a reference to it. So you need to drop the ().

Your code needs to look like this

setTimeout(myFunction,3000);

After you change it, you will get an alert every 3 seconds after you click ok and not a flood of alerts like you are seeing.

Upvotes: 3

Quentin
Quentin

Reputation: 943207

You are calling myFunction immediately and then passing its return value (undefined) to setTimeout

Remove the () so that you are passing the function instead of calling it.

Change:

setTimeout(myFunction(),3000);

To:

setTimeout(myFunction,3000);

Upvotes: 5

Related Questions