Search code examples
javascriptphplaravelcountdown

Run Function in Laravel after a certain time and show this time as a countdown


So I have a function and I want this function to run after(like 10 min) user selects it. While timer(10 min) is counting down to run this function, I want timer to be shown to user in a spesific view. I have all functions and views set up for this aim just I dont know how to put timer and show it to user.

https://www.w3schools.com/howto/howto_js_countdown.asp

I checked this but I cant properly put PHP values into Javascript so I cant make it. I also thought about cron jobs but I am not sure how I can do it there.

1) I want a function to run after a spesific time.

2) Additionally I would really like to show this time as a countdown to user.


Solution

  • If you want function that will run after certain time at serverside - check laravel.com/docs/5.5/scheduling. It's really easy to setup.

    You can create Laravel's with your function that will repeat every ten minutes or whatever you want. That job would get date from database and check if function should be executed - if so, mark database record with date as executed and call your function.

    For timer, in my opinion best approach is to make AJAX call to some API which would return your date for timer, then all need to be done is assign it to a javascript's variable. Another way is to render view template also with date, make it invisible with CSS display: none and then retrieve it from DOM for your JS timer.

    You would need make some changes to timer at w3schools. Add some conditionals to check how much time left, and if it's =< 10 minutes, append timer to the DOM.