Search code examples
javascripthtml5-canvastiming

How can I make a part of code wait without halting everything else in JavaScript?


So, I need to make a function wait a time interval before executing, however, I need the rest of the code to execute while this wait is happening. Basically, I want to change variables in function of time passed without having to make all code wait for that to be executed.

I'll give an example so you can understand me better.

function example(){
    sampleCode();
}

var x = 0;

if(x > 0){
    console.log("enough time has passed")
}

example();

Take in mind that the whole block of code is being repeated multiple times a second, it's not a single execution program. I need to make x greater than 0 without preventing "example" from executing, so, setInterval is a nono (unless it has a functionality I'm not aware of). How can I do this? (Ignore the fact that x is being defined in this scope, so it's being set to 0 over and over, pretend it's a global variable).

EDIT: I've been recommended to use setTimeout and to show how I use it, here's how:

function handleMouseClick(evt){
    [...]
    setTimeout(test(), 3000);
}

function test(){
    alert("Testing");
}

This results in an instant display of alert, no matter how much time i put into the timeout. What's wrong?


Solution

  • The issue you have is that you are not properly using the setTimeout function. You need to remove the parentheses from your call.

    setTimeout(test, 3000);
    

    Downvoters; I will make a more thorough and detailed answer for future readers later today when I’m at a computer. I am currently on break and do not have my computer with me. You can view some of my other answers to set your mind at ease that I will be back to flesh out a more detailed answer.