惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CXSECURITY Database RSS Feed - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
T
Threat Research - Cisco Blogs
小众软件
小众软件
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
Apple Machine Learning Research
Apple Machine Learning Research
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
V
V2EX
博客园 - 【当耐特】
C
Cybersecurity and Infrastructure Security Agency CISA
Hugging Face - Blog
Hugging Face - Blog
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
Simon Willison's Weblog
Simon Willison's Weblog
T
Threatpost
S
Secure Thoughts
O
OpenAI News
P
Proofpoint News Feed
S
SegmentFault 最新的问题
Forbes - Security
Forbes - Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
T
Tenable Blog
A
Arctic Wolf
L
LINUX DO - 热门话题
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Visual Studio Blog
Hacker News: Ask HN
Hacker News: Ask HN
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
博客园 - Franky
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
博客园_首页
雷峰网
雷峰网
IT之家
IT之家
PCI Perspectives
PCI Perspectives
L
LINUX DO - 最新话题
H
Heimdal Security Blog

JavaScript iDiallo.com

How to tell an element is in view using JavaScript. How to use pushState without breaking the back button How to create DOM elements efficiently with JavaScript Uncaught TypeError: Cannot read property of null Why Use Prototype in JavaScript Optimization: Minimize look-ups in for loops. Uncaught SyntaxError: Unexpected token < Magical JavaScript Live Collection Creating a class in JavaScript
Complex function call delays without nesting in JavaScript
Ibrahim Dial · 2023-10-27 · via JavaScript iDiallo.com

Complex function call delays without nesting in JavaScript

JavaScript Notes

Practical tips and subtle gotchas from real production experience.

I wanted to write a function that allowed me to wait for a specific time to run the code. The quick and dirty way to do it was to use setTimeout and nest callbacks. For example, at the end of an action, I would like to play an animation before I remove the element from the page. Let's see how we can do that with setTimeout.

function victoryDance(element) {
    // start the animation
    element.classList.add("animate");

    // after 2 seconds start the clean up
    setTimeout(() => {

        // stop the animation
        element.classList.remove("animate");

        // fade after 300 ms
        setTimeout(() => {
            // fade the element out
            element.classList.add("fade-out");

            // after 300 ms, remove the element
            setTimeout(() => {
                element.parentNode.removeChild(element);
            }, 300);
        }, 300);
    }, 2000);
}

The code is self-explanatory. victoryDance takes an element, animates it, stops the animation, fades the element out, then removes it from the DOM. As you can see, each action is nested into a setTimeout. The more actions I want to perform, the deeper I'd have to nest my functions. Instead, here is how I would like my code to look like instead.

function victoryDance(element) {
    // start the animation
    element.classList.add("animate");

    Util.wait(2)
    .then( wait => {
        element.classList.remove("animate");
        return wait(.3);        
    })
    .then( wait => {
        element.classList.add("fade-out");
        return wait(.3);
    })
    .then( wait => {
        element.parentNode.removeChild(element);
    });
}

This is much cleaner, and it is easier to read. If I want to add more delays, I can return wait at the end of each callback and add how much time I need to wait before the next action. To use the then() function, all we have to do is create a Promise. Here is the code.

// Nesting it inside util for portability
const Util = (() => {

    const wait = (delay) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(wait);
            }, delay * 1000);
        });
    };
    return {
        wait,
    };
})();

This is a simple function. wait() returns a Promise. Now when the timer times out, your function is called with a new wait promise as an argument that you can use to delay the next function call when it is resolved. Here is a generic way we can call it.

Util.wait(1)
.then(wait => {
    alert(1);
    return wait(2);
})
.then(wait => {
    alert(2);
    return wait(3);
})
.then(wait => {
    alert(3);
    return wait(4);
})
.then(wait => {
    alert(4);
});

When this is executed, alert is called after 1 second, then waits 2 seconds it is called again, then waits 3 seconds and it is called again, etc. This allows you to daisy chain timed actions one after another.


Did you like this article? Subscribe for more and follow updates via RSS.

Back to JavaScript articles