JS setTimeout()替代方案

9

就像我在这里解释的那样,我不能再使用window.setTimeout()和任何window经典函数,如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/

谢谢

2个回答

1
尝试使用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>


这个 {to:0} 和 {to:1} 表示什么?请澄清一下。 - JGV
2
$({to:0}) create a jQuery object where element at index [0] is the plain object {to:0}, we can call .animate() chained to the jQuery object which animates the to property from 0 to 1 - guest271314
对象进阶阅读:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects - brent_white

-6

这样的东西怎么样?

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有自己的Promise实现! jQuery Promise入门

请参阅此页面以获取文档。实现方式将类似。


谢谢 phenxd!它应该能解决问题。Promise 对于异步操作来说是一种优雅的解决方案。 - Mat Cloud
PB:在IE 9中未识别的承诺 :( - Mat Cloud
10
即使使用 Promise,这也不是异步的,而且当 while 循环正在工作时,界面将会被冻结,其他 JavaScript 代码也无法执行。 - Patrick Evans
哎呀,我是应该完全删除我的答案还是修改它? - phenxd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接