setTimeout,但在给定的时间 [英] setTimeout but for a given time

查看:99
本文介绍了setTimeout,但在给定的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么可以在JavaScript(即不通过插件),允许我做一些像 setTimeout ,但不是说在几毫秒应该发生,我给它一个日期对象告诉它什么时候做某事?

Is there anything readily available in JavaScript (i.e. not through "plugins") that allows me to do something like setTimeout, but instead of saying in how many milliseconds something should happen, I give it a date object telling it when to do something?

setToHappen(function () {
    alert('Wake up!');
}, new Date("..."));

是的,我知道我可以通过简单地减去 new Date )与我现有的日期对象(或者也可能是其他方式)得到毫秒数,但我仍然想知道。

And yes, I know I can do this by simply subtracting new Date() with my existing date object (or maybe it's the other way around) to get the amount of milliseconds, but I'd still like to know.

推荐答案

你必须找到现在和你的日期对象之间的毫秒数。

You'd have to just find the number of milliseconds between now and your date object.

function setToHappen(fn, d){
    var t = d.getTime() - (new Date()).getTime();
    return setTimeout(fn, t);
}

这篇关于setTimeout,但在给定的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆