How to delay function in C?

I can’t find a viable guide, so I ask, how can I postpone a function in C, in other words, how to make the program wait a certain number of seconds before continuing with other functions?

For instance:

printf("First Function.\n");

//program waits a certain number of seconds before executing next command

printf("Second function executed after certain amount of seconds");

I want to know which team I use to make this happen?

delay();

doesn't work for me, by the way.

I have to add, that sleep()doesn't work either.

+4
source share
4 answers

sleep - this is what you are looking for.

printf("First Function.\n");

sleep(20);  // Replace 20 with the "certain amount"

printf("Second function executed after certain amount of seconds")
+6
source

You can use Sleep () or select to add a delay.

+1
source

sleep() - POSIX. POSIX nanosleep(), .

thrd_sleep() C11 ( threads.h), AFAIK - glibc.

A simple sleep function can be implemented portable using functions from time.h:

#include <stdio.h>
#include <time.h>

void my_sleep(unsigned);
void delay_print(char *);

int main(void)
{
    delay_print("What is taking so long?");
    delay_print("Glad that over!");
}

void my_sleep(unsigned duration)
{
    time_t start = time(NULL);
    double end = duration;
    time_t now;
    do {
        now = time(NULL);
    } while (difftime(now, start) < end);
}

void delay_print(char *msg)
{
    my_sleep(5);
    puts(msg);
}
0
source

You can easily use:

sleep(unsigned int seconds);   //   from the unistid.h
Sleep(int milliseconds);       //   from the Windows.h
0
source

Source: https://habr.com/ru/post/1675986/


All Articles