Javascript - Thread Wait ?

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - About

JavaScript is a single-thread event-based model. Therefore, you don't want and can't stop the execution of code. May be with promise ?

3 - Wait

3.1 - Web API setTimeout

The setTimeOut is wrapper around code that create a job to execute it later. The execution of the thread (of the code) does not stop.

setTimeout put the function in the global scope.

setTimeout:

  • does not hold up execution, it executes the next line of the function immediately after the timeout is SET, not after the timeout expires.
  • does execute the code with eval. It means that the value of the called function parameters may have changed between the timeout and the execution of the code.

var countDelayedMessage = 0;
var countMessage = 0;
 
function printMessage(countMessage) {
    countDelayedMessage++;
    console.log("Count="+countDelayedMessage + ", countMessage="+countMessage);
}
 
/**
 * Add a message after a number of second
 * @param s A string
 * @param sec The number of second to wait
 */
function printMessageAfter() {
    countMessage++;
    window.setTimeout(function() { printMessage(countMessage) },countMessage*1000);
}
 
var button = document.getElementById("startButton");
button.addEventListener("click",
    function () {
        printMessageAfter();
        printMessageAfter();
        printMessageAfter();
        printMessageAfter();
}, false);
<button id="startButton">Start Demo</button>

countMessage is passed in the invocation of the function printMessage but the value uses is the the value of the call but of the execution (and therefore it will be always 4)

Advertising

3.2 - Promise

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');
}
 
var button = document.getElementById("startButton");
button.addEventListener("click", function () { demo() }, false);
<button id="startButton">Start Demo</button>

3.3 - JQuery

$('#warning')
.addClass('highlight')
.delay(1000)
.removeClass('highlight');

4 - Documentation / Reference

web/javascript/thread.txt · Last modified: 2019/02/16 17:40 by gerardnico