Image Image Image Image Image

© Copyright 2012 ABCoder | Email | RSS

Scroll to Top

To Top

Core JavaScript tips and tricks: playing with javascript

20

May
2008

27 Comments

In Core JavaScript

By

Javascript timer – advanced features, simple to use

On 20, May 2008 | 27 Comments | In Core JavaScript | By

javascript is the core of rich UI development and ajax driven website. i enjoy doing these. but in many cases, i thought things would be easier if the setTimeout(…) or setInterval(…) functions were simpler to handle. if you ever tried to make something like fadeout effect or accordion or anything that happens with a certain interval, you may understand what i mean. so, i thought it would be great to use a timer if anyone made already. i searched, got hundreds. but, none of them seemed perfect for me to use everywhere. for example, if you are familiar with visual basic (former) or .NET timer object, its very easy to use anywhere, anyhow. actually, this was the basic idea for my development (though it supports more than the basic).

so, i wrote a javascript timer object trying to provide a complete object oriented solution (basically for me, but you can use it too :) . its very simple to use, yet very powerful. you can set your desired interval and a callback function which will be called after each interval.

the simplest use would be:

var timer = new Timer(1000, myfunction);
timer.start();

first parameter sets the interval in milliseconds and second is the callback function to call. so, this will call myfunction() every second.

methods of Timer object and their parameters and return values (API reference) can be found here.

but, dont you want something more? well, in that case, first of all you should know that Timer object supports concatenation for almost every function. so you can rewrite the above code as:

var timer = new Timer(1000, myfunction).start();

whenever you want to stop the timer, just call:

timer.stop();

isn’t that simple? well, that’s just the beginning.

its time you are introduced to some necessary functions:

//pauses the timer
timer.pause();

//resumes the timer, if it was paused
timer.resume();

you should keep in mind that, there is a difference between stop() and pause(). when you pause the timer, it remembers how much of its interval is left. after resuming, it runs the remaining time of its interval. for example, if you set interval to 2000 milliseconds and pause the timer after running 1500 milliseconds; when you resume, it will call the callback function (i.e., myfunction ) after 500 milliseconds. this feature could be useful for rotating ads of news flashers in a website.

also, you have various functions like interval, addCallback, and many more. so, our very first code can be rewritten as:

var timer = new Timer().interval(1000).addCallback(myfunction).start();

or, to please eyes:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction)
.start();

note that, Timer class also supports empty constructor like Timer() which is my personal favorite.

wait.. where is the multiple callback feature? well here it is:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction1)
.addCallback(myfunction2)
//......
.addCallback(myfunctionN)
.start();

okay? well, you should know that functions are executed in parallel. if you dont trust me, try this:

var timer = new Timer();
timer.interval(1000)
.addCallback( function() { alert('hi there.'); } )
.addCallback(myfunction)
.start();

see, alert doesn’t block executing myfunction. i tried adding 20 callback functions. some of them showed time in a div, and some did something else. all of them executed in parallel. i.e., none block others’ execution.

well, so far everything runs forever unless you call timer.stop() or timer.pause(). what if you want the basic setTimeout(…) function back? there’s a way:

var timer = new Timer();
timer.interval(1000)
.addCallback(myfunction1)
.addCallback(myfunction2)
.runOnce(true)
.start();

this works same as setTimeout(…), i.e., executes myfunction1() and myfunction2() simultaneously one time after the specified interval. plus, you have the ability to stop or pause it anytime. is that sufficient for you? well, there’s more.

imagine, you are building an ajax driven webmail interface (for example, consider gmail). you have a clock showing current time in user’s inbox. also, you want to check if there is internet connection available in every 3 seconds. and you want to check for new mails in every 10 seconds. you may want more, but i will show you a skeleton program of these three feature using Timer object. your code should be something like this:

function update_clock(){
//code to update the clock
}

function check_connection(){
//code to check if there is connectivity with your server
//a simple XMLHttp request may be.
}

function check_mail(){
//an XMLHttp request to check for new mails
}

var timer = new Timer();
timer.interval(1000)
.addCallback(update_clock)
.addCallback(check_connection, 3)
.addCallback(check_mail, 10)
.start();

isn’t that too easy for that complex task? notice the second parameter in addCallback method. think like, the Timer object generates a pulse at given interval. the second parameter of addCallback method tells Timer object that this callback method should be executed at every Nth pulse; where N=1, 2, 3, … (here, N=3, 10). the seconds parameter, N, is optional and default value is 1.

now, off the record, someone asked me, if it can trigger a callback function (say, check_connection function from the example above) in 1.5 second interval!!! whoever is thinking to pass 1.5 (that is the quickest solution, i guess) as the second parameter, please dont. it only accepts integer number. but, there’s a work around. you need to learn some elementary math and come back here. then you will come-up with a solution like this:

var timer = new Timer();
timer.interval(500)
.addCallback(update_clock, 2)    //500 * 2 = 1000
.addCallback(check_connection, 3)    //500 * 1.5 * 2 = 1500
.addCallback(check_mail, 20)    //500 * 10 * 2 = 10000
.start();

thats a good solution and this is what i had in mind ;) . wait, one question is still hanging.

what will happen if i add .runOnce(true) just above .start() in the example above?

well, what is desired? i think, each callback function should be executed exactly once. thats what i implemented. so, regardless of continuous pulses provided by Timer object, update_clock() will execute exactly once after 1 sec, check_connection() will execute once after 1.5 sec and check_mail() will execute once after 10 sec. then the timer will stop. any suggestion?

well, there are still few more functions left to mention. but, they are too easy to explain. see API Reference for description/usage of functions of Timer object.

lastly be sure to have a good asp.net web hosting provider, it can make all the difference. for any suggestion, bug report or query, please leave a comment. hope you like it.

Links:

Tags | , , , , ,

Comments

  1. himel

    thanks for your information zpbappi. it was awesome. i m working on it. hope to hear some more from you.

  2. Thanks for clear and informative work.
    Just a suggestion: a countdown function would be nice.

  3. Not Bad

  4. Useful blog. good luck.

  5. Your blog is interesting!

    Keep up the good work!

  6. zp bappi

    thanks for all your comments. i’ll try to introduce something new.

    @shahin:
    it would be very easy. try the following (it assumes you have a div/span with id countdowndiv)

    var cntValue = 10;
    var timer = new Timer(1000);
    
    function updateCount(){
       if(cntValue < = 0){
          timer.clearCallbacks();
          return;
       }
       document.getElementById('countdowndiv').innerHTML = (--cntValue);
    }
    
    timer.addCallback(updateCount)
         .start();

    hope it works. let me know if it doesn’t.

    zp bappi.

  7. Eric Shepherd

    Nice work! This is exactly what I was looking for. I’m curious about one thing, though – why did you remove the constructor into the instances with the init() function? I moved it back into the constructor and nothing seems to break.

    Thanks!

  8. zp bappi

    @Eric Shepherd
    i moved the initialization codes into a method “_init()” just to keep the default constructor clean. there’s no harm if i put the codes in “var Timer = function(millis, callback){…}”.

    thanks for trying it differently. let me know if there is any improvement i can do, or anything you came up with.

    zp bappi.

  9. Great site. Good info
    viagra

  10. The article on antibiotics are very good.

  11. The best information i have found exactly here. Keep going Thank you

  12. darck

    In my opinion start and stop shouldn’t alter paused state of timer. In borland delphi’s timer is option enabled. Maybe you can change pause functionality or add enabled state. It works simply as pause – timer doesn’t count ticks and enabled property is not related with any other method.

  13. Ricardo Verhaeg

    One suggestion is: you could pass a third parameter or even an optional second (with type check) to match the “runOnce”, why is that?
    A – Perhaps I want to keep the clcok running but only check my mail once (in the given example) so I’ld put something like:

    var timer = new Timer();
    timer.interval(1000)
    .addCallback(clock)
    .addCallback(checkMail,10,true)
    .start();

    or:

    var timer = new Timer();
    timer.interval(1000)
    .addCallback(clock)
    .addCallback(somethingInOneSecond,true)
    .start();

    But well I’m really impressed of the fact that you made it with parallel! I was really trying to find that out! thanks!

  14. @darck: sorry, i am not familiar with delphi’s timer. and, when you start/stop a timer, it should not remember where it was paused. that’s true to the most of the people. please explain why it shouldn’t be altered. (with some test case, if needed)

    @ricardo verhaeg: thanks for your suggestion. i have many other things too for the next version. but, i am not getting enough free time to complete it. i will do it soon i hope and will post a link here.

  15. darck

    1)
    var timer = new Timer();
    timer.interval(10000)
    .addCallback(clock)
    .start()
    .stop();

    timer.start();

    should work exactly same as:

    2)
    var timer = new Timer();
    timer.interval(10000)
    .addCallback(clock)
    .start();

    timer.restart();

    and different than:

    3)
    var timer = new Timer();
    timer.interval(10000)
    .addCallback(clock)
    .start()
    .pause();

    timer.start();

    1) and 2) should restart timer counter before starting countdown again, but 3) should only pause counter and resume it when invoked start() again.

  16. @darck: i believe you want the start method to work as resume if the timer is paused. right? well, thats what i did. please check the api page (links at the bottom of the post) for start method. it says, “Starts the timer initially or if it was stopped. If timer was paused, start work as resume.”
    hope that helps. :)

  17. famictech2000

    Is there a way to add a paramtere list to the callback function? This would allow for much more functionalty. If so can you please share!

    • yes. there is.
      say, your callback function is:

      function addNumbers(a, b){
      //your code here
      //...
      }

      then, you use the timer callback as:

      var tmr = new Timer(1000);
      tmr.addCallback(function(){ addNumbers(3, 5); });
      tmr.start();

      got the idea?

  18. famictech2000

    Yup got it! You are the best!

    Thanks for the help!

  19. Hey there what do you think is the next world war close?

  20. Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

  21. the following Javascript timer – advanced features, simple to use is bound to have saved me when I say a ton of time in getting a genuinely brilliant read in detail

  22. Amazing

    Can you add a reset() function?

    • Amazing

      NVM, just read about restart()

  23. Mikael

    Thanks, great work, THANK you as a former flash developer I really miss this function. this function handles iteration through time very well.

    Mikael

  24. Hi guys,

    Thank you for your support. I am thinking of extending it’s functionality. I already have few things in my TODO list. Being able to add callback with “NumberOfTimesToRun” (which includes runOnce if you pass 1) individually is the most important among them. There are also few places for optimization. Do you have anything in your mind? Let me know. I am starting soon. Very soon.

Submit a Comment