How to Add a Delay for a 2 or 3 Seconds

How do I add a 3 seconds delay to this function?

Look into setTimeout. e.g. setTimeout(myFunction, 3000) will call myFunction in 3 seconds.

        $(document).ready(function() {
$('body').addClass('js');
var $menu = $('#menu'),
$menulink = $('.menu-link');
$menulink.click(function() {
$menulink.toggleClass('active');
$menu.toggleClass('active');

// If I'm understanding the question correctly,
// you want the menu to go away after 3 seconds
setTimeout(function() {
$menulink.toggleClass('active', false);
$menu.toggleClass('active', false);
}, 3000);
return false;
});
});

Flutter - How to delay a function for some seconds

You'll have to add an helper variable in the outer scope, that will indicate whether the user is on an answer cooldown or not.

The shortest solution will be:

var answerCooldownInProgress = false;
tappedbutton(int index) async {
// Ignore user taps when cooldown is ongoing
if (answerCooldownInProgress) {
return;
}
final userAnswer = await userAnswer();
if (userAnswer) {
// ...
} else {
ErrorSnackbar();

answerCooldownInProgress = true;
await Future.delayed(const Duration(seconds: 2));
answerCooldownInProgress = false;
}
}

Is there a best method to implement a delay in between threads?

A more 'canonical' way to tackle this problem in .Net is using the Task Parallel Library instead of manually controlling threads. The console program below illustrates how you would run 6 threads on background threads, with a one second delay between them.

class Program
{
public async static Task Main()
{
var cts = new CancellationTokenSource();

List<Task> tasks = new List<Task>();

for (int i = 0; i < 6; i++)
{
tasks.Add(Task.Run(() => DoWork(cts.Token), cts.Token));
await Task.Delay(1000);
}

Console.WriteLine("Press ENTER to stop");
Console.ReadLine();
Console.WriteLine("Waiting for all threads to end");
cts.Cancel();
await Task.WhenAll(tasks);
}

public static void DoWork(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Console.WriteLine($"Doing work on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(10000); // simulating 10 seconds of CPU work;
}
Console.WriteLine($"Worker thread {Thread.CurrentThread.ManagedThreadId} cancelled");
}
}

Asynchronous programming using the Task Parallel Library is explained pretty well in the documentation

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
System.out.println("Running");
}

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
// Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.



Related Topics



Leave a reply



Submit