JS setTimeout() alternative
JS setTimeout() alternative
就像我在这里解释的那样,我不能再使用window.setTimeout()和任何窗口经典函数,如clearInterval等...);但是我需要调用JS块代码作为异步代码。
这就是我使用 XHR 请求的原因。
使用 XHR 实现 window.setTimeout() 的智能替代方案的最佳方法是什么?
// Not working :(
setTimeout(function(){
document.getElementById("messageTimer").innerHTML = "Happy New Year ! (old version)";
}, 10);
// with or without jQuery - but XHR
jQuery.ajax({
url: "/local/url/easy",
success: function(html, textStatus, jqXHR) {
// a loop ?
// timeout done ?
document.getElementById("messageTimer").innerHTML = "Happy New Year ! (working version)"
}});
我的小提琴测试:https://jsfiddle.net/mlefree/xzh3w2we/
啧
尝试使用
jQuery 版本 3.0 .animate()
,现在使用 requestAnimationFrame
// Creates a jQ object where elem set to index of [0]
// a plain object with value of 0 `{to:0}`
// call .animate() chained to the jQ object
// Animates `{to:0}` value from 0 - 1
// $({to:0}).animate({to:1}
var duration = 5000;
$({to:0}).animate({to:1}, duration, function() {
// do stuff after `duration` elapsed
$("#messageTimer").html("Happy New Year ! (working version)")
})
<script src="https://code.jquery.com/jquery-3.0.0-beta1.min.js"></script>
<div id="messageTimer"></div>
这样的事情呢?
var delay = 10000; // milliseconds
var before = Date.now());
while (Date.now() < before + delay) {};
alert('The delay has passed!');
此外,您可能对 Promise 对象感兴趣。这可能会给你这样的忧郁:
var customDelay = new Promise(function(resolve) {
var delay = 10000; // milliseconds
var before = Date.now();
while (Date.now() < before + delay) {};
resolve('Success!');
});
customDelay.then(function(msg) {
document.getElementById("messageTimer").innerHTML = "Happy New Year !';
});
---编辑---Promise 对象是 ECMAScript 6 的一部分,因此会出现向后兼容性问题。
幸运的是,jQuery确实有自己的Promises实现!jQuery Promise 简介
有关文档,请参阅此页面。实现将是类似的。
相关文章:
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- Ember Data DS.Model's set函数不起作用
- C#asp.net mvc Set CheckBoxFor已检查的具有Model Value的属性
- 为什么JavaScript可以'找不到给定的InnerHTML并返回Cannot set property
- 无法在基于Cordova的应用程序中读取Set Cookie标头
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- 为什么可以't我用Set对象调用Array.prototype.map
- Sequelize associations:set[Models]添加新模型,而不是关联现有模型
- 如何使用选项useCSS set true为bxSlider加载onSlideAfter()事件
- Node JS,传统的数据结构?(如Set等),任何类似Java.util的node
- Bootstrap-Datepicker not selecting date when using "set
- Looking for function identical to lodash's [_.set]()
- Angular sqlLite set css url()无法设置相对路径
- Typerror:set 不是带有 angularjs 的函数
- 在使用 findAndModify 时$set运算符中将函数参数作为字段名称传递
- Javascript Regex Lookbehind Alternative
- fabric.js:使用 Image.set() 调整图像大小是否会降低图像质量
- dataTransfer.set拖放的数据在chrome中不起作用
- 在 app.locals 上设置属性和调用 app.set() 有什么区别?
- console.log 在 CasperJS 的 set Timeout 评估中不起作用