Ok, I got this <button onclick="alert('1');setInterval(function(){},57000);alert('2');"> Show </button>
The delay didn't work.
setTimeout also didn't work.
How to fix it?
Ok, I got this <button onclick="alert('1');setInterval(function(){},57000);alert('2');"> Show </button>
The delay didn't work.
setTimeout also didn't work.
How to fix it?
Put the alert inside the setInterval callback:
<button onclick="alert('1');setInterval(function(){alert('2');},57000);"> Show </button>
Simple extended version of your code:
var div = document.querySelector('div');
function myFunction(){
div.textContent += '-';
// beware, this code might crash your browser if left running
// for a few (thousand) years!!!
}
<button onclick="setInterval(myFunction, 1000);"> Start Interval </button>
<div></div>
A properly styled version of the code above:
var div = document.getElementById('d');
var button = document.getElementById('b');
button.addEventListener('click', clickHandler);
function myFunction(){
div.textContent += '-';
// beware, this code might crash your browser if left running
// for a few (thousand) years!!!
}
function clickHandler(){
setInterval(myFunction, 1000);
}
<button id="b"> Start Interval </button>
<div id="d"></div>
JavaScript code runs synchronously, which means that each instruction is executed one after another. Let's take a look at your code:
alert('1');
setInterval(function(){
//does nothing
}, 57000);
alert('2');
Now each line will execute one after the other, which means alert(1) will execute, then setInterval(...) and then alert(2). Your setInterval doesn't stop the other lines from executing.
If you want to have a delay on your code execution, you must consider having that code execute after your setInterval (I'm assuming you want to use setTimeout here) finishes.
Also, as a pro-top, you should separate your JavaScript code from your HTML. Let's consider the following:
<button id="myButton">Show</button>
...
<script>
// Get a reference to your button
var myButton = document.querySelector('#myButton');
// The code you want to execute after the given time
function executeLater(){
alert(2);
}
// We attach an event listener to your button
myButton.addEventListener('click', function(){
alert('1');
setTimeout(executeLater, 2000);
});
</script>