简体   繁体   中英

Wait before next function not working

I need to wait 5 seconds before running the second line:

 function waitnext() { setTimeout('', 5000); alert('waited'); } 

However it seems to open the alert instantly when the function is run. Any idea how to fix this? Thanks

 function waitnext() { setTimeout( function(){ alert('waited'); }, 5000); } waitnext(); 

Your syntax is wrong. Here you go with the documentation https://www.w3schools.com/jsref/met_win_settimeout.asp

Put the line you want to run after some delay as a callback of setTimeout

function waitnext() {
    setTimeout(function() {
        alert('waited'); // runs after 5000ms
    }, 5000);
}

setTimeout evaluates a callback function after a specified number of milliseconds has elapsed.

Solution using ES6.

 let waitnext = () => { setTimeout(() => { // callback alert('waited'); }, 5000); } waitnext(); 

Or using ES5:

 'use strict'; var waitnext = function waitnext() { setTimeout(function () { // callback alert('waited'); }, 5000); }; waitnext(); 

function waitnext(){
 setTimeout(function(){
 alert('waited');
}, 5000);

Try this

a few samples ...

 var myAlarm = e => console.log(e);
 var myStop = () => console.log('stop');
 var wait = (delay, callback) => setTimeout(callback, delay);

 wait(2000, () => myAlarm("finished after 2 seconds"));
 wait(3000, myStop);

 // the following line don´t work ...
 // the function was executed immediately
 wait(4000, myAlarm('cheesecake'));

//use setTimeout 
setTimeout(myStop, 1000);
// the following line don´t work ...
// the function was executed immediately
setTimeout(myAlarm('cheesecake'),3000);
// this works
setTimeout(() => myAlarm('cheesecake'),3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM