JS setTimeout() alternative

后端 未结 2 873
余生分开走
余生分开走 2021-02-15 11:27

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

2条回答
  •  粉色の甜心
    2021-02-15 12:00

    What about something like this?

    var delay = 10000; // milliseconds
    var before = Date.now());
    
    while (Date.now() < before + delay) {};
    
    alert('The delay has passed!');
    

    Also, you might be interested in the Promise objects. Which could give you somtehing like this :

    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 !';
    });
    

    ---EDIT--- The Promise object is part of ECMAScript 6 so there will be backward compatibility issues.

    Luckily for you, jQuery does have it's own implementation of Promises! Introduction to jQuery Promises

    See this page for documentation. Implementation will be similar.

提交回复
热议问题