JS setTimeout()替代 [英] JS setTimeout() alternative

查看:392
本文介绍了JS setTimeout()替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我在这里解释这里一样,我不能再使用window.setTimeout()和任何窗口经典函数,如clearInterval等...);但我需要将JS块代码称为异步版。

Like i explain here , i can't use window.setTimeout() anymore and any window classical functions like clearInterval etc ...); but i need calling a JS block code as an async one.

这就是我使用XHR请求的原因。

That's why i used XHR request.

使用XHR实现window.setTimeout()的智能替代方法的最佳方法是什么?

What is the best way to implement a smart alternative to window.setTimeout() with XHR ?

// 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 /

Tks

推荐答案

尝试使用< a href =http://blog.jquery.com/ =nofollow noreferrer> 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>

这篇关于JS setTimeout()替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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