Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS setTimeout() alternative

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.

That's why i used XHR request.

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)"
 }});

My fiddle test : https://jsfiddle.net/mlefree/xzh3w2we/

Tks

like image 514
Mat Cloud Avatar asked Feb 01 '16 14:02

Mat Cloud


People also ask

What can I use instead of setTimeout?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.

Is setTimeout deprecated in JavaScript?

We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);

Is there any delay function in JS?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

How do you wait 1 second in JavaScript?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.


1 Answers

Try using jQuery version 3.0 .animate(), which now uses 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>
like image 53
guest271314 Avatar answered Nov 15 '22 05:11

guest271314