Jquery倒计时计时器与到期回调

jquery count down timer with expiry callback?

本文关键字:回调 倒计时 计时器 Jquery      更新时间:2023-09-26

我正在使用keith-wood插件来生成一个计数计时器。
它工作得很好,但当使用回调选项我有问题

 $(document).ready(function(){ 
            function timerdone(){
                alert('welcome');
            }
                    $('#id').countdown({
                                 until: +300, 
                                 compact: true,
                                 onExpiry: timerdone,
                                 format: 'HMS'
                             });  
                })

对于上面的例子,它的工作没有问题,但问题是当一个变量传递给回调函数,页面调用函数一旦加载

$(document).ready(function(){ 
                function timerdone(msg){
                    alert(msg);
                }
                        $('#id').countdown({
                                     until: +300, 
                                     compact: true,
                                     onExpiry: timerdone('welcome'),
                                     format: 'HMS'
                                 });  
                    })
onExpiry: function() {
    timerdone('welcome');
},

不调用您的函数,而是使用匿名函数将其作为引用传递。

展开@Brad M的回答——

你在JS中犯了一个相对常见的错误——不是传递一个函数的引用,而是调用它并传递它的返回值。

// in the following, onExpiry is expecting a function reference 
// (also called a function handle). The function will be invoked
// later on.
...
onExpiry: timerdone,
// this worked fine, you were passing a reference to the function
onExpiry: timerdone(), 
// this MISTAKE is something many people do. It is invoking the function (with
// no arguments) and then sending the function's return value for <onExpiry>
onExpiry: timerdone('welcome'),
// this was your MISTAKE. Same as above, you're invoking the function instead
// of sending the function reference as is expected. You're invoking
// the function with 1 argument, but the argument isn't the issue. The issue
// is that you're invoking the function and sending its result (return
// value) as <onExpiry> 
// 
// There are different ways to fix it, @Brad's solution is a good one.
var counter = $('#counter');
var due = new Date();
due.setHours(due.getHours()+24);
due.setSeconds(due.getSeconds() + 3);
var dueMinus24Hours = new Date(due);
dueMinus24Hours.setHours(due.getHours()-24);
var timeout = dueMinus24Hours-new Date();
setTimeout(function() {
    counter.countdown('option', { format: 'HMS' });
}, timeout);
counter.countdown({
        until: due,
        format: 'OD',
        padZeroes: true
    });