glemiere
glemiere

Reputation: 5026

Best way to execute code at given datetime in JavaScript

I'd just like to know which method would be the best to execute a function at a given date in JS. My first idea is to make a loop running in a web worker checking each minute if I'm in the minute where I'm supposed to display my notification, but I wonder if there is a cleaner way to make it.

Any idea ?

PS : I don't really need any answer because I'm using the cordova plugin local-notifications and I'm using the 'at' argument, this question is for pure curiosity/learning.

EDIT : Some of you find the question too broad, in fact it's broad, not too broad (I'm not asking "How to send notifications ?") and that's all the point, I'm looking for a general algorithm/explanation to have a rich answer here, so explanations for any platforms are welcomed to help to grasp the differences of the problem each time.

Upvotes: 0

Views: 70

Answers (1)

Geuis
Geuis

Reputation: 42267

Well it really depends on your where your application will live. If its in the browser, node, etc.

The simplest but also fragile solution would be to calculate the difference in milliseconds between now and the execution time. Then just setTimeout() with that difference. But if the browser refreshes, then of course that timeout is gone unless you run the same thing again.

But without knowing more about the structure and nature of your application, its difficult to get any more specific.

Upvotes: 1

Related Questions