1

I have looked at many Posts regarding setInterval and none of them have the answer I am looking for or what I am trying to achieve what I want.

I am looking for one setInterval function with 2 clicks. The first click is separated by 2sec from the 2nd click. It only runs once What I have at the moment is a workaround using two functions, it works.. but I would rather have them in one function rather than two functions.

The first click is immediate runs in one seconds (1000)it closes the open modal. Then the next click is after 2 seconds(2000) it removes a clone. Below is what I am using at the moment with in my $each. Thanks for your help.

$.each(deleteCard, function( i, person ) {
    setTimeout(function() {  
        $("#"+person.id).find('.close-modal').click(); 
    }, 1000);

    setTimeout(function() { 
        $("#"+person.id).find('.card').remove(); 
    }, 2000);  
}); 
zhulien
  • 5,145
  • 3
  • 22
  • 36
Jvaskana
  • 53
  • 9

1 Answers1

1

I don't think setInterval will help here. It's a poor choice for only repeating something twice (your original code also had an irregular delay, something setInterval doesn't do well).

I'd uses promises and write a wait function as a general utility you can tuck away in a helper file somewhere:

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

$.each(deleteCard, async function (i, person) {
  await wait(1000);
  $("#" + person.id).find('.close-modal').click();
  await wait(1000);
  $("#" + person.id).find('.card').remove();
});
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Thank you ggorlan. Your solution sound very good. I think I will ammend the timing 1000 on my example as 30 stood for immidiate as 1000 was one sec and of course 2000 is 2 sec. Idid not want to have to use an external file, only if I really have too. So I would like to see what other suggestions come. – Jvaskana Feb 21 '21 at 00:30
  • If your intent was to fire something immediately, then you can skip the first `wait`/`setTimeout` entirely and just use a single `setTimeout` with a delay of 2000 ms, so there's no need for this abstraction if it's the only time you're doing this. You don't _have_ to have an external file, that's just a suggestion to illustrate that the "client" code is very clean. If you find your code is cluttered with `setTimeout`s you have the ability to promisify `setTimeout` once and use `wait` throughout the codebase. – ggorlen Feb 21 '21 at 00:31