how to do a sleep in javascript?

1

Try this but it did not work:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}

demo();

In my case I added the demo function to my javascript so that before it closes, it does a sleep but never does it and closes before, the code:

/** Represents a timer that can count down. */
function CountdownTimer(seconds, tickRate) {
    this.seconds = seconds || (25*60);
    this.tickRate = tickRate || 500; // Milliseconds
    this.tickFunctions = [];
    this.isRunning = false;
    this.remaining = this.seconds;



    /** CountdownTimer starts ticking down and executes all tick
        functions once per tick. */
    this.start = function() {
        if (this.isRunning) {
            return;
        }

        this.isRunning = true;

        // Set variables related to when this timer started
        var startTime = Date.now(), 
            thisTimer = this;

        // Tick until complete or interrupted
        (function tick() {
            secondsSinceStart = ((Date.now() - startTime) / 1000) | 0;
            var secondsRemaining = thisTimer.remaining - secondsSinceStart;

            // Check if timer has been paused by user
            if (thisTimer.isRunning === false) {
                thisTimer.remaining = secondsRemaining;
            } else {
                if (secondsRemaining > 0) {
                    // Execute another tick in tickRate milliseconds
                    setTimeout(tick, thisTimer.tickRate);
                } else {

                    // Stop this timer
                    thisTimer.remaining = 0;
                    thisTimer.isRunning = false;

                    // Alert user that time is up
                    playAlarm();
                    playAlarm();
                    changeFavicon('green');

                    //run again
                    demo();
                    demo();
                    demo();


                    var elemento = document.getElementById('btn_shortbreak');
                    elemento.click();



                }

                var timeRemaining = parseSeconds(secondsRemaining);

                // Execute each tickFunction in the list with thisTimer
                // as an argument
                thisTimer.tickFunctions.forEach(
                    function(tickFunction) {
                        tickFunction.call(this, 
                                          timeRemaining.minutes, 
                                          timeRemaining.seconds);
                    }, 
                    thisTimer);
            }
        }());        
    };


    this.close = function(){
        window.close();
    };
    /** Pause the timer. */
    this.pause = function() {
        this.isRunning = false;
    };

    /** Pause the timer and reset to its original time. */
    this.reset = function(seconds) {
        this.isRunning = false;
        this.seconds = seconds
        this.remaining = seconds
    };


    /** Add a function to the timer's tickFunctions. */
    this.onTick = function(tickFunction) {
        if (typeof tickFunction === 'function') {
            this.tickFunctions.push(tickFunction);
        }
    };
}

/** Return minutes and seconds from seconds. */
function parseSeconds(seconds) {
    return {
        'minutes': (seconds / 60) | 0,
        'seconds': (seconds % 60) | 0
    }
}

/** Play the selected alarm at selected volume. */
function playAlarm() {
    var alarmValue = document.getElementById('alarm_select').value;
    if (alarmValue != 'none') {
        var alarmAudio = document.getElementById(alarmValue);
        var alarmVolume = document.getElementById('alarm_volume').value;
        alarmAudio.volume = alarmVolume / 100;
        alarmAudio.play();
    }
}


function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  console.log('Taking a break...');
  await sleep(10000);
  console.log('Two second later');
}



/** Change the color of the favicon. */
function changeFavicon(color) {
    document.head = document.head || document.getElementsByTagName('head')[0];
    var color = color || 'green';

    var newFavicon = document.createElement('link'),
        oldFavicon = document.getElementById('dynamic-favicon');
    newFavicon.id = 'dynamic-favicon'
    newFavicon.type = 'image/ico';
    newFavicon.rel = 'icon';
    newFavicon.href = 'images/' + color + '_tomato.ico';

    if (oldFavicon) {
        document.head.removeChild(oldFavicon);
    }
    document.head.appendChild(newFavicon);
}

/** Window onload functions. */
window.onload = function () {

     playAlarm();

    var timerDisplay = document.getElementById('timer'),
        customTimeInput = document.getElementById('ipt_custom'),
        timer = new CountdownTimer(),
        timeObj = parseSeconds(25*60);

    /** Set the time on the main clock display and
        set the time remaining section in the title. */
    function setTimeOnAllDisplays(minutes, seconds) {
        if (minutes >= 60) {
            // Add an hours section to all displays
            hours = Math.floor(minutes / 60);
            minutes = minutes % 60;
            clockHours = hours + ':';
            document.title = '(' + hours + 'h' + minutes + 'm) Pomodoro';
        } else {
            clockHours = '';
            document.title = '(' + minutes + 'm) Pomodoro';
        }

        clockMinutes = minutes < 10 ? '0' + minutes : minutes;
        clockMinutes += ':';
        clockSeconds = seconds < 10 ? '0' + seconds : seconds;

        timerDisplay.textContent = clockHours + clockMinutes + clockSeconds;
    }

    /** Revert the favicon to red, delete the old timer
        object, and start a new one. */
    function resetMainTimer(seconds) {
        changeFavicon('red');
        timer.pause();
        timer = new CountdownTimer(seconds); 
        timer.onTick(setTimeOnAllDisplays);
    }

    // Set default page timer displays
    setTimeOnAllDisplays(timeObj.minutes, timeObj.seconds);

    timer.onTick(setTimeOnAllDisplays);

    resetMainTimer(5*60);
    timer.start(); 

    var elemento = document.getElementById('btn_shortbreak');
                    elemento.click()

    // Add listeners for start, pause, etc. buttons
    document.getElementById('btn_start').addEventListener(
        'click', function () { 
            timer.start(); 
        });

    document.getElementById('btn_pause').addEventListener(
        'click', function () {
            timer.pause(); 
        });

    document.getElementById('btn_reset').addEventListener(
        'click', function () {
            resetMainTimer(timer.seconds);
            timer.start();
        });

    document.getElementById('btn_pomodoro').addEventListener(
        'click', function () {
            resetMainTimer(25*60);
            timer.start();
        });

    document.getElementById('btn_shortbreak').addEventListener(
        'click', function () {
            resetMainTimer(5*60);
            timer.start();
            window.close();
        });

    document.getElementById('btn_longbreak').addEventListener(
        'click', function () {
            resetMainTimer(15*60);
            timer.start();
        });

    document.getElementById('btn_custom').addEventListener(
        'click', function () {
            customUnits = document.getElementById('custom_units').value
            if (customUnits === 'minutes') {
                resetMainTimer(customTimeInput.value*60);
            } else if (customUnits === 'hours') {
                resetMainTimer(customTimeInput.value*3600);
            } else {
                resetMainTimer(customTimeInput.value);
            }
            timer.start();
        });

    // Bind keyboard shortcut for starting/pausing timer
    Mousetrap.bind('space', function(e) { 
        // Remove default behavior of buttons (page scrolling)
        if (e.preventDefault()) {
            e.preventDefault();
        } else {
            e.returnValue = false; //IE
        }

        // Pause or start the timer
        if(timer.isRunning) {
            timer.pause();
        } else {
            timer.start();
        }
    });


    resetMainTimer(5*60);
            timer.start();

};

Any possible way to do a sleep in javascript to pause before I close my page using javascript?

    
asked by Sergio Ramos 28.02.2018 в 15:26
source

2 answers

1

But it does not make sense to use promises to make a sleep.

If what you want to do is execute a code after x milliseconds without blocking the execution of the rest of the code you just have to call the setTimeout method.

If you want the execution thread to stop x milliseconds completely blocking all the code and continuing after that time you would need a "sleep" function, but with synchronous execution. Something like this:

function sleep(milliseconds) {
 var start = new Date().getTime();
 for (var i = 0; i < 1e7; i++) {
  if ((new Date().getTime() - start) > milliseconds) {
   break;
  }
 }
}

function demo() {
  console.log('Taking a break...');
  sleep(2000);
  console.log('Two second later');
}

demo();

If you want to have an asynchronous behavior, as I said before, you only have to do setTimeout :

function demo() {
  console.log('Taking a break...');
  setTimeout(console.log.bind(null, 'Two second later'), 2000);
}

demo();

The sleep function is taken from: JavaScript. Sleep function - JS Pills

    
answered by 28.02.2018 в 15:37
0

In this part:

//run again
demo();
demo();
demo();

var elemento = document.getElementById('btn_shortbreak');
elemento.click();

You are running asynchronous functions and then clicking on the button that triggers the closure. So clearly the execution continues without waiting for the term of demo()

If instead you had executed in the demo body:

async function demo() {
    console.log('Taking a break...');
    await sleep(2000);
    console.log('Two second later');
    var elemento = document.getElementById('btn_shortbreak');
    elemento.click();
}

You would have obtained the behavior you were looking for

    
answered by 28.02.2018 в 15:48