PDA

View Full Version : Set time out for a local function : setimeout(this.func, timeout)



hieu79vn
22 Sep 2012, 8:37 AM
Hi all,

Is there any way to set time out for a local function such as pollForWindowClosure, like this

setTimeout(function(){this.pollForWindowClosure(myWindow)}, 10);

Thank you

talha06
22 Sep 2012, 1:23 PM
You can manually define a function that counts down and then a callback function can be triggered.

hieu79vn
23 Sep 2012, 10:52 PM
Hi talha06

Could you give an example?

Thank you

talha06
23 Sep 2012, 10:58 PM
A simple one, you can use this:

function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};

function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}

this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};

this.stop = function () {
clearInterval(timer);
};

}

hieu79vn
23 Sep 2012, 11:02 PM
Hi talha

Really I dont know how to apply your code to my case.

How can we catch the onclose of the popup with your code? and how we set the callback function for it?

Thanks

talha06
23 Sep 2012, 11:06 PM
Just create a new Countdown instance then set duration with using seconds config (number of seconds).

The other options you need to use:

onUpdateStatus : A function that is called after each interval
onCounterEnd : A function that is called after countdown is finished


var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});

myCounter.start();