jquery.wakeup.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*!
  2. * jQuery WakeUp plugin
  3. *
  4. * A JQuery plugin that will help detecting waking up from sleep and/or
  5. * hibernation and executing assigned functions.
  6. *
  7. * Based on code provided by Andrew Mu:
  8. * http://stackoverflow.com/questions/4079115
  9. *
  10. * Copyright (c) 2013, Paul Okopny <paul.okopny@gmail.com>
  11. *
  12. * Permission to use, copy, modify, and/or distribute this software for any
  13. * purpose with or without fee is hereby granted, provided that the above
  14. * copyright notice and this permission notice appear in all copies.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  17. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  19. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  20. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  21. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  22. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  23. *
  24. */
  25. (function ($, document, undefined) {
  26. var default_wakeup_interval = 1000;
  27. var wake_up_ids = new Array();
  28. // returns intervalId, which can be used to cancel future waking
  29. $.wakeUp = function (on_wakeup, params, interval) {
  30. if ((!interval) || typeof(interval) !== 'number' ){
  31. interval = default_wakeup_interval;
  32. };
  33. // on_wakeup should be a function
  34. if (typeof(on_wakeup) !== "function") {
  35. return null;
  36. }
  37. var lastTime = (new Date()).getTime();
  38. var intervalId = setInterval(function() {
  39. var currentTime = (new Date()).getTime();
  40. if (currentTime > (lastTime + interval + 1000)) { //
  41. var sleepTime = currentTime - lastTime;
  42. lastTime = currentTime;
  43. if (params) {
  44. on_wakeup(sleepTime, params);} else {on_wakeup(sleepTime); }
  45. } else {lastTime = currentTime;}
  46. }, interval);
  47. //add interval id to wake_up_ids array
  48. wake_up_ids.push(intervalId);
  49. return intervalId;
  50. };
  51. $.ignoreBell = function(interval_id) {
  52. if (interval_id) {
  53. // delete only one wakeUp call
  54. wake_up_ids.splice($.inArray(interval_id, wake_up_ids),1);
  55. clearInterval(interval_id);
  56. };
  57. };
  58. $.dreamOn = function() {
  59. // delete all current wake Up calls
  60. $.each(wake_up_ids, function(index_of, interval_id) {
  61. clearInterval(interval_id)
  62. });
  63. wake_up_ids = new Array();
  64. };
  65. })(jQuery, document);