Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
How to use several setTimeout one by one?

I would like to animate text decryption. For ex., I have the encrypted text **** long ********* **** and I would like to slowly replace it with some long encrypted text.

I tried to use the code below, but it replaces the text immediately when I need to pause after each symbol is replaced.

function play(encText, decrText) {

    function showText() {
        var text = decrText.substring(0, i+1) + encText.substring(i+1);
        console.log(text);
        document.getElementById('text').innerHTML = text;
    }

    for( var i=0; i < encText.length+1; i++ ) {
        setTimeout( showText(), i*5000 );
    }

}

See https://jsfiddle.net/bwf0Layg/.

How could I fix that?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can create a closure for you showText on your i loop, by returning a function.

Also, I've changed you innerHTML to innerText, to stop some funky things happening, and decreased the time from 5 seconds for demo purposes.

eg.

function play(encText, decrText) {
    function showText(i) {
       return () => {
         var text = decrText.substring(0, i + 1) + 
            encText.substring(i + 1);
         document.getElementById('text').innerText = text;
       }
    }

    for (var i = 0; i < encText.length + 1; i++) {
       setTimeout(showText(i), i * 100);
    }
}

play(document.getElementById('text').innerText, 'some long encrypted text')
<div id="text">
**** long ********* ****
</div>

about 4 years ago · Juan Pablo Isaza Report

0

The problem with your code is that the last run writes all the letters at once. What you could do is create a sleep function with a promise and setTimeout

const sleep = ()=> new Promise((resolve)=> setTimeout(resolve,5000));

async function play(encText, decrText) {
      function showText(i) {
        var text = decrText.substring(0, i + 1) + encText.substring(i + 1);
        console.log(text);
        document.getElementById('text').innerHTML = text;
      }

      for (let i = 0; i < encText.length + 1; i++) {
        await sleep();
        showText(i)
      }

    }

so on every iteration, your code "sleeps" or awaits for 5 seconds before moving to the next iteration making this slow letter appearance.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!