-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)"
user3541562
  • 251
  • 2
  • 3
  • 9
  • If you search for (and write about) the *actual problem* then it's easier to find duplicates - "not working" is *not* a valid diagnosis. – user2864740 May 11 '14 at 01:06
  • http://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout?lq=1 , http://stackoverflow.com/questions/4120781/settimeout-ignores-timeout-fires-immediately – user2864740 May 11 '14 at 01:07
  • This code hurts my eyes. This is 2014 already, don't use `onclick` and look at that incorrect use of `setTimeout`. – Derek 朕會功夫 May 11 '14 at 01:09
  • @Derek I am new to javascript.if there is any better way then pls tell – user3541562 May 11 '14 at 01:13
  • Have a look at these articles to learn about the different ways to bind event handlers: http://www.quirksmode.org/js/introevents.html. – Felix Kling May 11 '14 at 01:46

2 Answers2

4

remove parenthesis, change:

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

to

onclick="setTimeout(rating, 3000)"

or better way would be:

onclick = setTimeout(function() {
    rating();
}, 3000);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • The "better way" is incorrect - it will spawn the timer first, then pass an (invalid) numeric value to the onclick property. – user2864740 May 11 '14 at 01:45
1
onclick="setTimeout(rating, 3000)" // rating without the ()

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

NoGray
  • 1,149
  • 7
  • 9