Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setTimeout doesn't work [duplicate]

I wanted a JavaScript function to run 60 seconds after page is loaded. After a little research I have made, I've found that setTimeout() is the solution.

So that's what I did:

<body onLoad="setTimeout(postAction('news.reads', 'article'), 60000);">

Somehow, setTimeout does not work. After the page is loaded, there's no need to wait 60 seconds because postAction() runs immediately.

Why is it happening? How to solve it? Are there alternatives to setTimeout() up there? Thank you!

like image 213
Ido Avatar asked Jun 12 '26 07:06

Ido


1 Answers

You need to wrap postAction in a function to defer execution:

setTimeout(function() { postAction('news.reads', 'article'); }, 60000);

You are actually executing postAction immediately, your code is equivalent to:

var result = postAction('news.reads', 'article');

setTimeout(result, 60000);
like image 151
Mike Valenty Avatar answered Jun 14 '26 21:06

Mike Valenty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!