-1

I am trying to call a javascript function at the onclick of an html element as shown below. But not sure why the below timeout function is not working here.Any idea

onclick="setTimeout(rating(), 3000)"
5
  • If you search for (and write about) the actual problem then it's easier to find duplicates - "not working" is not a valid diagnosis. Commented May 11, 2014 at 1:06
  • stackoverflow.com/questions/7137401/… , stackoverflow.com/questions/4120781/… Commented May 11, 2014 at 1:07
  • This code hurts my eyes. This is 2014 already, don't use onclick and look at that incorrect use of setTimeout. Commented May 11, 2014 at 1:09
  • @Derek I am new to javascript.if there is any better way then pls tell Commented May 11, 2014 at 1:13
  • Have a look at these articles to learn about the different ways to bind event handlers: quirksmode.org/js/introevents.html. Commented May 11, 2014 at 1:46

2 Answers 2

4

remove parenthesis, change:

onclick="setTimeout(rating(), 3000)"

to

onclick="setTimeout(rating, 3000)"

or better way would be:

onclick = setTimeout(function() {
    rating();
}, 3000);
Sign up to request clarification or add additional context in comments.

1 Comment

The "better way" is incorrect - it will spawn the timer first, then pass an (invalid) numeric value to the onclick property.
1
onclick="setTimeout(rating, 3000)" // rating without the ()

When you include the parentheses, the function return value is used instead of the function itself.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.