javascript - js : trigger a timing event after pause/resume

标签 javascript

我想在特定时间后触发一些事件。计时器应该是可暂停的。 这是代码: http://jsfiddle.net/xsH8v/

问题是我怎样才能触发这个

  if (Clock.totalSeconds >= givenTime){
    alert('time is up!');
  }

我把它放在 document.ready 里了。但是当时间到了时它不会被解雇。我认为问题在于根本没有调用该函数。如果是这样,我该如何触发它?

最佳答案

您的方法不起作用,因为 if 语句只计算一次;在文档加载时。要解决此问题,您需要添加每次更新 totalSeconds 时都会检查的回调。

这是我的解决方案; fiddle here

您可以使用 Clock.at(time, callback) 添加函数,如下所示:

Clock.at(10, function() {/* 10 秒过去了 */});

var Clock = {
    totalSeconds: 0,

    handlers: [],

    start: function () {
        var self = this;

        this.interval = setInterval(function () {
            self.totalSeconds += 1;

            sec = parseInt(self.totalSeconds % 60)
            min = Math.floor(self.totalSeconds / 60 % 60)
            hour = Math.floor(self.totalSeconds / 3600)

            $("#hour").text(hour);
            $("#min").text(min);
            $("#sec").text(sec);

            // Fire each expired handlers
            self.handlers = self.handlers.filter(function(handler) {

                if (self.totalSeconds >= handler.time) {
                    // Fire the handler then remove it
                    handler.func();
                    return false;
                }

                return true;
            })

        }, 1000);
    },

    pause: function () {
        clearInterval(this.interval);
        delete this.interval;
    },

    resume: function () {
        if (!this.interval) this.start();
    },

    at: function(time, handler) {

        // Handle expired handlers
        if (this.totalSeconds >= time) handler();

        // Add the handler to the queue
        this.handlers.push({
            time: time,
            func: handler,
        });
    }
};

关于javascript - js : trigger a timing event after pause/resume,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21794971/

相关文章:

javascript - 在一行 CSS 中自动淡入和淡出相同的图像

javascript - VueJs - 将创建的项目推送到现有数组并使其与其他现有项目一起显示

javascript - Chartjs x 轴缩放

javascript - 本地存储保存多个相同项目

javascript - 如果 esModuleInterop 为 true 配置 TypeScript 转译,我是否需要显式 allowSyntheticDefaultImports?

javascript - 如何从 JSON 恢复原始对象/类型?

javascript - 即使我在函数外部初始化变量,也不会打印该值

javascript - 使用动态属性键获取 javascript 对象的属性值

javascript - Meteor:检查用户是否阅读消息

javascript - for 循环和索引数组不起作用