努力使用精确的setInterval / setTimeout替换

Struggling to use accurate replacement for setInterval / setTimeout

本文关键字:setInterval setTimeout 替换 努力      更新时间:2023-09-26

我试图使用的代码在底部(从这里)在超大的jquery插件(这里)。这是因为我需要一个更准确的计时器,因为我正在同步图像和声音。

基本上,supersize有这些行:

vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);

clearInterval(vars.slideshow_interval); 

我需要这样做:

vars.slideshow_interval = accurateInterval(base.nextSlide, base.options.slide_interval);

vars.slideshow_interval.clear();

问题我的javascript技能有些有限,我甚至不知道术语/描述下面的函数,我想它需要在基础的形式。accurateInterval = function(time fn)..而不是包装,因为我怀疑问题与在错误的上下文中使用(this)有关。

我尝试按原样使用代码,当我调用clear()时,我得到"不是函数错误"。

我怎么才能让它工作呢?任何提示,非常感谢。谢谢你!

(function () {
    window.accurateInterval = function (time, fn) {
        var cancel, nextAt, timeout, wrapper, _ref;
        nextAt = new Date().getTime() + time;
        timeout = null;
        if (typeof time === 'function') _ref = [time, fn], fn = _ref[0], time = _ref[1];
        wrapper = function () {
            nextAt += time;
            timeout = setTimeout(wrapper, nextAt - new Date().getTime());
            return fn();
        };
        cancel = function () {
            return clearTimeout(timeout);
        };
        timeout = setTimeout(wrapper, nextAt - new Date().getTime());
        return {
            cancel: cancel
        };
    };
}).call(this);

(function () { … }).call(this);包装器是一个coffeescript特性,用于确保this等于全局对象,实际上在这里根本不需要。window.accurateInterval = …足以使函数全局化。

当调用clear()时,我得到'is not a function error'。

这是因为accurateInterval返回一个具有 cancel 方法的对象。使用

vars.slideshow_interval.cancel();